在 Kona session ,构造函数的模板参数推导(P0091R0)已获批准。它简化了一些变量定义:
std::pair p {1,2}; // o.k., constructor pair<int,int>(1,2)
std::vector v1 (10, 0); // o.k., 10 zeroes, constructor vector<int>(size_t n, T initvalue)
std::vector v2 {10, 0}; // o.k., 2 values: 10, 0, apparently initializer list?
std::vector v3 = {10, 0}; // o.k., same as v2?
但是,以下行不能在 gcc 7 HEAD 201611 版本 ( live example ) 中编译:
std::vector v4 = {3}; // error: no matching function for call to 'std::vector(int)'
std::vector v5 {1, 2, 3}; // error: 'int' is not a class
std::set s {1, 2, 3}; // error: no matching function for call to 'std::set(int,int,int)'
因为它们涉及初始值设定项列表,它们是否只是“太过分的桥梁”? 它们是否包含在模板类型参数推导中? 当编译器符合 C++1z 时,它们会被允许吗?
最佳答案
您需要一对额外的大括号才能使您的代码正常工作:
std::vector v4 = {{1, 5}};
std::vector v5 {{1, 2, 3}};
std::set s {{1, 2, 3}};
关于c++ - 从初始化列表中推导构造函数的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40692796/