C ++ template function with an unknown number of arguments

this is probably a useless problem, but it stuck with me for several hours.

I want to write a function that takes some (POD) arguments, converts them to a string and returns concatenation. eg

template<typename A, typename B>
string ToString(A a, B b)
{
    stringstream ss;
    ss << a << b;
    return ss.str();
}

pretty easy, huh? but for me it is quite difficult (for me, of course) when I want to write the same function with the number of unknown arguments.

Is it possible? any solution?

+2
source share
3 answers

Almost like a real thing :-)

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

template<class L,class R>
struct cons_t
{
    const L &l; const R &r;
    cons_t(const L &_l, const R &_r) : l(_l),r(_r) {}
};
template<>
struct cons_t<void,void>{};
typedef cons_t<void,void> cons;

template<class L,class R,class A>
cons_t< cons_t<L,R>, A> operator , (const cons_t<L,R> &l, const A &arg)
{
    return cons_t< cons_t<L,R>, A>(l,arg);
}
void to_stream(stringstream &s, const cons_t<void,void> &) { }
template<typename L, typename R>
void to_stream(stringstream &s, const cons_t<L,R> &c)
{
    to_stream(s, c.l); 
    s << c.r;
}
template<typename L, typename R>
string to_string(const cons_t<L,R> &c)
{
    stringstream ss;
    to_stream(ss,c);
    return ss.str();
}

#define ToString(...) to_string((cons(),__VA_ARGS__))
int main()
{
    cout << ToString(1,2,"Hi There",3.14159);
}
+5
source

In C ++ 03, no. All you can do is create overloads with a different number of arguments:

template<typename A, typename B>
string ToString(A a, B b)
{
    stringstream ss;
    ss << a << b;
    return ss.str();
}

template<typename A, typename B, typename C>
string ToString(A a, B b, C c)
{
    stringstream ss;
    ss << a << b << c;
    return ss.str();
}

() Boost.Preprocessor.

++ 0x , :

#include <iostream>

void f()
{
}

template <class T, class ... Ts>
void f(const T& a, const Ts&... args)
{
  std::cout << a;
  f(args...);
}
+9

I know that this is probably an academic problem, and therefore the solution to work does not look like what you want.

But.

An easy way to handle this in real life would be to pass objects to a List or Array, rather than have a few parameters.
You know how Main ()

+1
source

All Articles