模板和标准::p空气列表初始化
Templates and std::pair list-initialization
这是这个问题的后续。
为什么会编译:
#include <iostream>
class Test {
public:
Test(std::pair<char *, int>) {
std::cout << "normal constructor 2!" << std::endl;
}
};
int main() {
Test t6({"Test", 42});
return 0;
}
但这不会:
#include <iostream>
class Test {
public:
Test(std::pair<char *, int>) {
std::cout << "normal constructor 2!" << std::endl;
}
template<typename ... Tn>
Test(Tn ... args) {
std::cout << "template constructor!" << std::endl;
}
};
int main() {
Test t6({"Test", 42});
return 0;
}
错误信息:
错误:对"Test"构造函数的调用不明确
正如我在上一个问题中所理解的,如果非模板构造函数完全匹配,则首选非模板构造函数。所以我想{"测试",42}与std::p air不匹配?如果是这样,正确的方法是什么?我知道有 std::make_pair,但我希望它尽可能短,因为我可以有几对这样的对,每次输入 std::make_pair 都是不利的,因为它会膨胀事情。那么最短的方法是什么?
由于您已经在使用 c++11,请切换到大括号初始化,您的代码将在 gcc(至少 4.7.2)下编译并执行您想要的操作:
...
int main() {
Test t6{{"Test", 42}};
return 0;
}
$ g++ t.cpp -std=c++11
t.cpp: In function ‘int main()’:
t.cpp:14:25: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
$ a.out
normal constructor 2!
相关文章:
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 复制列表初始化的隐式转换的等级是多少
- LNK2038、MSVS2017 MAGMA的原因列表
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 没有为自己的结构调用列表推回方法
- 使用简单类型列表实现的指数编译时间.为什么
- 一对向量构造函数:初始值设定项列表与显式构造
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 通过for循环使用用户输入填充列表
- C++:如何使函数只返回作为列表一部分的字符串
- 概念中的cv限定符需要表达式参数列表
- 下面是我为检测链接列表中的循环而制作的代码
- 建议在运行时将带有类实例的列表从c++导入qml
- 如何维护资源管理器项目视图中当前可见的项目列表
- 标准::p空气<矢量、双精度的初始值设定项列表<int>>
- 模板和标准::p空气列表初始化