在 C++ 中,是否可以创建一个同时采用类类型和可变数量参数的模板化函数?我想象的函数会像这样工作(尽管这显然不是正确的语法,因为当我尝试它时它不起作用):
// definition
template <class T, class... Args>
T* myFunc(Args... args) {
T* newObj = new T(args);
return newObj;
}
// usage
class MyClass {
int myA;
float myB;
bool myC;
public:
MyClass(int a, float b, bool c) {
myA = a;
myB = b;
myC = c;
}
}
class OtherClass {
char otherA;
int otherB;
public:
OtherClass(char a, int b) {
otherA = a;
otherB = b;
}
}
MyClass* myPtr = myFunc<MyClass>(5, 3.0, true);
OtherClass* otherPtr = myFunc<OtherClass>('h', 572);
我知道您可以创建模板函数,该函数可以在调用函数时使用尖括号中指定的类型,而且我也知道可以创建接受任何类型的多个输入值的可变参数模板函数,但我还没有这样做过能够找到有关结合这两种技术的任何信息。
这样的事可能吗?
您需要使用
args
将 ...
展开为一个包,如下所示:
template <class T, class... Args>
void myFunc(Args... args) {
T newObj(args...);
// do stuff with the new object
}