模板和std ::对列表初始化 [英] Templates and std::pair list-initialization

查看:199
本文介绍了模板和std ::对列表初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是问题。

为什么编译:

#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'的构造函数是不明确的

error: call to constructor of 'Test' is ambiguous

,如果它非常匹配,则非模板构造函数是优选的。所以我猜{Test,42}与std :: pair不匹配?
如果是这样,什么是正确的方式?我知道有std :: make_pair,但我想要尽可能短,因为我可以有几个这些对,并键入std :: make_pair每次都会不利,因为它膨胀的东西。

As I understood in the previous question, the non-template constructor is preferred, if it exactly matches. So I guess {"Test", 42} does not match with std::pair? If so, what would be the correct way? I know there is std::make_pair, but I want it as short as possible, because I can have several of those pairs and typing std::make_pair everytime would be unfavorable, because it bloats things. So what is the shortest way possible?

推荐答案

因为你已经在使用c ++ 11 ,切换到大括号初始化,你的代码将编译在gcc(至少4.7.2),并做你想要的:

Since you're already using c++11, switch to brace initialization and your code will compile under gcc (4.7.2 at least) and do what you want:

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

这篇关于模板和std ::对列表初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆