You are not logged in.

#1 2012-07-23 13:49:33

snack
Member
From: Italy
Registered: 2009-01-13
Posts: 876

Variable arguments in C++

Hi, I'm facing a problem in C++ which I cannot solve (I hope it is solvable...). I have many concrete implementations of an abstract class, each of them with a different number and types of constructor arguments. I would like to build such objects by using a "factory" singleton class, whose Build method will call one of the constructors of the various concrete classes, depending on the value of a Build's argument. My problem is: how can I pass the variable constructor argument list to Build?
Here's a brief example: suppose I have these two concrete classes:

class Concrete1: public BaseClass{
public:
  Concrete1(int arg1);
}

class Concrete2: public BaseClass{
public:
  Concrete2(float arg1, const char *arg2);
}

The Build method of the singleton factory would look as:

BaseClass *Factory::Build(int type, other arguments}){
  if (type == 1)
    return new Concrete1(arguments);
  if (type == 2)
    return new Concrete2(arguments);
}

I can use the variable arguments list syntax ... to pass "other arguments" to Build, but then I would need to know number and types to correctly pass them to the different constructors. I know I can do it with a list format argument:

BaseClass *Factory::Build(int type, const char *format, ...)

but then the invocation would become somewhat awkward:

Factory::Build(2, "fs", 4.2, "whatever");

and then in Build I have to parse the format string: first character "f" indicates a float first argument, the second character "s" a string second argument and so on. I wonder whether I am doing everything in the best possible way or if there are smarter ways...
Any help or tip will be greatly appreciated smile
Thanks!

Last edited by snack (2012-07-23 13:50:49)

Offline

#2 2012-07-23 13:52:50

Allan
Pacman
From: Brisbane, AU
Registered: 2007-06-09
Posts: 11,498
Website

Re: Variable arguments in C++

Seems a problem for variadic templates in c++11 (http://en.wikipedia.org/wiki/Variadic_template)

Offline

#3 2012-07-23 16:11:07

snack
Member
From: Italy
Registered: 2009-01-13
Posts: 876

Re: Variable arguments in C++

Thanks Allan. Variadic templates worked like a charm (I only have to pay some attention to cast variable arguments to correct types when invoking Build).
I have another question: my final goal would be to write python bindings for Factory, so that I could build the various objects from the python shell, and not build them in C++ code. I think this is not trivial since I need to somehow specify the variadic templates at compile time, right?

Offline

Board footer

Powered by FluxBB