c++variadic-functionsfunction-templates

Function that takes both variadic arguments and a class type?


In C++, is it possible to create a templated function which takes both a class type and a variable number of arguments? The function I'm imagining would work something like this (although this is clearly not the right syntax, since it doesn't work when I try it):

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

I know you can create template functions that work with a type specified in angle brackets when the function is called, and I also know that it's possible to make variadic template functions which take multiple input values of any type, but I haven't been able to find any information on combining those two techniques.

Is such a thing possible?


Solution

  • You just need to expand the pack args using ellipsis ... as shown below:

    template <class T, class... Args>
    T* myFunc(Args... args) {
      T* newObj = new T(args...);
      return newObj;
    }
    

    Working demo


    Don't forget to use delete or better yet use smart pointer like auto newObj = std::make_unique<T>(args...);