C ++ how to define a function without knowing the exact parameters

I have a template function

template <class T>
void foo() {
  // Within this function I need to create a new T
  // with some parameters. Now the problem is I don't
  // know the number of parameters needed for T (could be
  // 2 or 3 or 4)
  auto p = new T(...);
}

How can i solve this? Somehow I remember seeing functions with input as (..., ...)?

+5
source share
2 answers

Here is an example of how C ++ 11 works for you based on a variation template :

#include <utility> // for std::forward.
#include <iostream> // Only for std::cout and std::endl.

template <typename T, typename ...Args>
void foo(Args && ...args)
{
    std::unique_ptr<T> p(new T(std::forward<Args>(args)...));
}

class Bar {
  public:
    Bar(int x, double y) {
        std::cout << "Bar::Bar(" << x << ", " << y << ")" << std::endl;
    }
};

int main()
{
    foo<Bar>(12345, .12345);
}

Hope this helps. Good luck

+1
source

You can use variable templates:

template <class T, class... Args>
void foo(Args&&... args){

   //unpack the args
   T(std::forward<Args>(args)...);

   sizeof...(Args); //returns number of args in your argument pack.
}

This question contains more detailed information on how to unpack arguments from a variational template. This question here may also provide additional information.

+6
source

All Articles