5

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 (..., ...)?

WhatABeautifulWorld
  • 2,830
  • 2
  • 19
  • 28
  • 5
    Keywords to look for: varargs, variable length argument list, variadic templates. (However, your code snippet seems strange, there is nothing in there that you could pass to T's constructor.) – us2012 Mar 04 '13 at 17:45
  • 2
    If you don't know the number of parameters, how do you know what values to pass? – Bo Persson Mar 04 '13 at 17:47
  • Use this link http://stackoverflow.com/questions/3307939/c-template-function-with-unknown-number-of-arguments – Viswanath Lekshmanan Mar 04 '13 at 17:52
  • Use this [link][1] [1]: http://stackoverflow.com/questions/3307939/c-template-function-with-unknown-number-of-arguments Follow the first answer. – Viswanath Lekshmanan Mar 04 '13 at 17:54

2 Answers2

6

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

Community
  • 1
  • 1
Tony The Lion
  • 57,181
  • 57
  • 223
  • 390
  • 2
    You mean `template`. Your edits are not making any sense :-). You need `Args` to be passed to the function, not `T`. Also, use `std::forward` when passing the arguments to the constructor. – Praetorian Mar 04 '13 at 17:53
2

Here is the working C++11 example for you based on a variadic 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 it helps. Good Luck!