int main(){
int x{};
auto x2 = x;
auto x3{x};
static_assert(is_same<int, decltype(x)>::value, "decltype(x) is the same as int");
static_assert(is_same<int, decltype(x2)>::value, "decltype(x2) is the same as int");
static_assert(is_same<int, decltype(x3)>::value, "decltype(x3) is the same as int"); // Error here.
}
这段代码不能用 gcc 4.8.0 编译。
我什至不猜测 decltype(x3)
的类型。它是什么?为什么行为不同?
最佳答案
#include <initializer_list>
#include <type_traits>
using namespace std;
int main(){
int x{};
auto x2 = x;
auto x3{x};
static_assert(is_same<int, decltype(x)>::value, "decltype(x) is the same as int");
static_assert(is_same<int, decltype(x2)>::value, "decltype(x2) is the same as int");
static_assert(is_same<std::initializer_list<int>, decltype(x3)>::value, "decltype(x3) is the same as int");
}
这将编译。 x3
被推断为 std::initializer_list<int>
由于:
Let
T
be the type that has been determined for a variable identifierd
. ObtainP
from T [...] if the initializer is a braced-init-list (8.5.4), withstd::initializer_list<U>
.
关于c++ - 为什么 auto 的推论不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16692499/