Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

c++ - When should I use decltype(x) instead of auto to declare the type of a variable?

I see decltype(x) used inside macros where x is a variable name because the type of the object isn't known inside macros.

For example:

decltype(x) y = expr;

I could just have easily use auto instead of decltype. So what are those situations where decltype is needed for a variable type declaration instead of auto?

question from:https://stackoverflow.com/questions/21369131/when-should-i-use-decltypex-instead-of-auto-to-declare-the-type-of-a-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

decltype becomes handy when you need to return some unknown type, which is evaluated during compilation:

template<class A, class B>
void MultiplyAB(A a, B b, decltype(a*b)& output)
{
    output = a * b;
}

Additionally, if you don't like the way the output is handled by a reference, then you can also use the late-specified return type (and also use the decltype):

template<class A, class B>
auto MultiplyAB(A a, B b) -> decltype(a*b)
{
    return a * b;
}

All of this, and more, is described by B. Stroustrup in the C++ FAQ.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...