将构造函数与固定参数混合,构造函数与构造函数模板混合

时间:2014-01-03 00:27:55

标签: c++ c++11 variadic-templates

是否可以将构造函数与固定参数和构造函数模板混合使用?

我的代码:

#include <iostream>

class Test {
    public:
        Test(std::string, int, float) {
            std::cout << "normal constructor!" << std::endl;
        }

        template<typename ... Tn>
        Test(Tn ... args) {
            std::cout << "template constructor!" << std::endl;
        }
};

int main() {
    Test t("Hello World!", 42, 0.07f);
    return 0;
}

这给了我“模板构造函数!”。有没有办法,我的普通构造函数被调用了?

2 个答案:

答案 0 :(得分:6)

当然,如果有两个同样好的匹配,则首选非模板:

Test t(std::string("Hello"), 42, 0.07f);

答案 1 :(得分:3)

C ++知道两种基本字符串类型:std::string null - 终止字符数组。而不是将问题解决方法(如Kerrek SB建议的那样),您可以添加另一个重载:

class Test {
public:
    Test(std::string, int, float) {
        std::cout << "normal constructor!" << std::endl;
    }

    Test(const char*, int, float) {
        std::cout << "normal constructor 2!" << std::endl;
    }

    template<typename ... Tn>
    Test(Tn ... args) {
        std::cout << "template constructor!" << std::endl;
    }
};

Live example

您还可以使用委托构造函数来实现另一个正常构造函数,以避免重复代码,例如。

Test(const char* c, int i, float f)
    : Test(std::string(c), i, f)
{
}

Live example

相关问题