模板和标准::p空气列表初始化

Templates and std::pair list-initialization

本文关键字:空气 列表 初始化 标准      更新时间:2023-10-16

这是这个问题的后续。

为什么会编译:

#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!