据我了解, decltype 和 auto 都将试图弄清某种事物的类型.
As I understand it, both decltype and auto will attempt to figure out what the type of something is.
如果我们定义:
int foo () { return 34; }这两个声明都是合法的:
Then both declarations are legal:
auto x = foo(); cout << x << endl; decltype(foo()) y = 13; cout << y << endl;能否请您告诉我 decltype 和 auto 之间的主要区别是什么?
Could you please tell me what the main difference between decltype and auto is?
推荐答案decltype 给出传递给它的表达式的声明的类型. auto 的作用与模板类型推导相同.因此,例如,如果您有一个返回引用的函数,则 auto 仍将是一个值(您需要 auto& 来获取引用),但decltype 将恰好是返回值的类型.
decltype gives the declared type of the expression that is passed to it. auto does the same thing as template type deduction. So, for example, if you have a function that returns a reference, auto will still be a value (you need auto& to get a reference), but decltype will be exactly the type of the return value.
#include <iostream> int global{}; int& foo() { return global; } int main() { decltype(foo()) a = foo(); //a is an `int&` auto b = foo(); //b is an `int` b = 2; std::cout << "a: " << a << '\n'; //prints "a: 0" std::cout << "b: " << b << '\n'; //prints "b: 2" std::cout << "---\n"; decltype(foo()) c = foo(); //c is an `int&` c = 10; std::cout << "a: " << a << '\n'; //prints "a: 10" std::cout << "b: " << b << '\n'; //prints "b: 2" std::cout << "c: " << c << '\n'; //prints "c: 10" }另请参阅DavidRodríguez关于仅在 auto 或 decltype 之一可能出现的位置的答案.
Also see David Rodríguez's answer about the places in which only one of auto or decltype are possible.
更多推荐
十进制vs自动
发布评论