模板和 std::pair 列表初始化

2023-12-20

这是后续this https://stackoverflow.com/questions/20894459/mixing-constructors-with-fixed-parameters-and-constructors-with-constructor-temp问题。

为什么会这样编译:

#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”构造函数的调用不明确

正如我在上一个问题中所理解的,如果完全匹配,则首选非模板构造函数。所以我猜 {"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!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

模板和 std::pair 列表初始化 的相关文章

随机推荐