1

Is is possible to create a template method with flexible parameter list, like this:

class TestA
{
  public:
    TestA(int i, int j) { ... }
}
class TestB
{
  public:
    TestB(std::string a) { ... }
}

class Base
{
  public:
    template<class T>
    bool add( ... )
    {
        ... new T( **PARA** );
     }    
}

With PARA replaced by the parameter list. Class TestA and TestB knows which parameter they need ( how much parameters and type ) so it would be possible with va_args?

Is there a better way of doing it ?

base.add<TestA>(1,2);
base.add<TestB>( "abc" );
Roby
  • 2,011
  • 4
  • 28
  • 55

1 Answers1

7

Yes, you're looking for variadric templates. They will let you have exactly the functionality you desire:

template<class T, class... Args>
bool Base::add(Args&&... args) {
    // ...
    T myT(std::forward<Args>(args)...);
    // ... 
}

Note that even if none of your arguments are rvalue references, you still should use both Args&& and std::forward (unless you explicitly want to enforce a copy, of course). These will collapse into the appropriate reference types as necessary.

VF1
  • 1,594
  • 2
  • 11
  • 31