Mixing constructors with fixed parameters and constructors with constructor templates

可紊 提交于 2019-12-07 08:38:50

问题


Is it possible to mix constructors with fixed parameters and constructor templates?

My Code:

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

This gives me "template constructor!". Is there a way, that my normal constructor is called?


回答1:


Sure, in the event of two equally good matches, the non-template is preferred:

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



回答2:


C++ knows two basic string types: std::string and null-terminated character arrays. Instead of fixing your problem on the caller's side (as Kerrek SB suggested), you could add another overload:

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

You could also use delegating constructors to implement one of the normal constructors in terms of the other to avoid duplicating the code, e.g.

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

Live example



来源:https://stackoverflow.com/questions/20894459/mixing-constructors-with-fixed-parameters-and-constructors-with-constructor-temp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!