11
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). 它是什么?为什么行为不同?

4

2 回答 2

12
#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是已为变量标识符确定的类型dP如果初始值设定项是一个花括号初始化列表(8.5.4),则从 T [...]获取,使用std::initializer_list<U>.

于 2013-05-22T13:07:11.203 回答
6

所以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>
于 2013-05-22T13:08:46.180 回答