问题
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