views:

78

answers:

1

Hello

I wanted to write a function with a variable argument list. I want to explore my options. I'm pretty sure I came accross a boost template class that was designed for this purpose, but I can't think of the name of it? Can anyone tell me? or did I dream this up! Thanks

+4  A: 

If you only need to accept a variable count of arguments of the same type, taking a container would be the common thing to do. Creation of the container however can be eased using Boost.Assign:

void f(const std::vector<int>& vec) {}
f(boost::assign::list_of(1)(2)(3)(4));

Alternatively you can go for operator overloading (e.g. of operator() or operator<<) yourself, similar to the approach taken by the standard library streams:

op() << arg1 << arg2 << arg3;

If you really want to provide a type-safe variadic function (without using C++0x features), Boost.Preprocessor can help. A generic example:

#define OUT(z, n, name) << name ## n

#define MAKE_FUNC(z, n, unused)                                     \
    template<class T BOOST_PP_ENUM_TRAILING_PARAMS(n, class T)>     \
    void func(T t BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n, T, t) ) { \
        std::cout << t BOOST_PP_REPEAT(n, OUT, t) << std::endl;     \
    }

BOOST_PP_REPEAT(9, MAKE_FUNC, ~) // generates func() versions taking 1-10 arguments
func(1, "ab", 'c'); // prints "1abc"
Georg Fritzsche