同时采用可变参数和类类型的函数?

问题描述 投票:0回答:1

在 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);

我知道您可以创建模板函数,该函数可以在调用函数时使用尖括号中指定的类型,而且我也知道可以创建接受任何类型的多个输入值的可变参数模板函数,但我还没有这样做过能够找到有关结合这两种技术的任何信息。

这样的事可能吗?

c++ variadic-functions function-templates
1个回答
0
投票

您需要使用

args
...
展开为一个包,如下所示:

template <class T, class... Args>
void myFunc(Args... args) {
  T newObj(args...);
  // do stuff with the new object
}
© www.soinside.com 2019 - 2024. All rights reserved.