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)的类型。那是什么?为什么行为是不同的?
发布于 2013-05-22 21:07:11
#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>:
假设
T是已为变量标识符d确定的类型。从T获取P...如果初始值设定项是带括号的初始化列表(8.5.4),则使用std::initializer_list<U>。
发布于 2013-05-22 21:08:46
所以x3实际上是一个std::initializer_list<int>,你可以通过下面的方法弄清楚这一点:
std::cout << typeid(x3).name() << std::endl ;对我来说,我有以下输出:
St16initializer_listIiE通过c++filt实现此功能
c++filt -t St16initializer_listIiE给了我:
std::initializer_list<int>https://stackoverflow.com/questions/16692499
复制相似问题