Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

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 do I solve this? Somehow I remember saw functions with input like (..., ...)?

like image 907
WhatABeautifulWorld Avatar asked Mar 04 '13 17:03

WhatABeautifulWorld


1 Answers

You could use variadic 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 here has more detail on how to unpack arguments from a variadic template. This question here may also provide more information

like image 138
Tony The Lion Avatar answered Sep 25 '22 21:09

Tony The Lion