c++ - 为什么 auto 的推论不同?

标签 c++ c++11 type-inference

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 identifier d. Obtain P from T [...] if the initializer is a braced-init-list (8.5.4), with std::initializer_list<U>.

关于c++ - 为什么 auto 的推论不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16692499/

相关文章:

c++ - 带有 CDT 的 Eclipse Juno 不添加内置包含目录

C++11 共享指针 vector 和内存泄漏

c++ - 自动生成函数头,可变参数模板

c++ - QTcpSocket模拟netcat 'conversation'

android - unw_init_remote 因 UNW_EBADREG 而失败

c++ - std::set 在使用 std::set.erase 后包含重复元素

c++ - 用 C++ 实现的类型推断

typescript - 在 for ... in 循环中进行类型推断

javascript - Flowtype - flowtype 可以自动注释变量的类型吗?

c++ - libmediainfo 有替代方案吗?