gpt4 book ai didi

c++ - 模板和 std::pair 列表初始化

转载 作者:搜寻专家 更新时间:2023-10-31 01:46:16 25 4
gpt4 key购买 nike

这是 this 的后续行动问题。

为什么编译:

#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;
}

错误信息:

error: call to constructor of 'Test' is ambiguous

正如我在上一个问题中所理解的,非模板构造函数是首选,如果它完全匹配的话。所以我猜 {"Test", 42} 与 std::pair 不匹配?如果是这样,正确的方法是什么?我知道有 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!

关于c++ - 模板和 std::pair 列表初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20895216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com