MBZ*_*MBZ 2 c++ templates function
这可能是一个无用的问题,但它在我的脑海里停留了几个小时.
我想编写一个接受一些(POD)参数的函数,将它们转换为字符串并返回串联.例如
template<typename A, typename B>
string ToString(A a, B b)
{
stringstream ss;
ss << a << b;
return ss.str();
}
Run Code Online (Sandbox Code Playgroud)
很简单,对吧?但是当我想用未知数量的参数编写相同的函数时,它(当然对我来说)变得相当困难.
它甚至可能吗?任何解决方案
jpa*_*cek 10
在C++ 03中,没有.您所能做的就是使用不同数量的参数创建重载:
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();
}
Run Code Online (Sandbox Code Playgroud)
这可以通过Boost.Preprocessor库自动(某种程度上).
在C++ 0x中,您可以使用如下的可变参数模板:
#include <iostream>
void f()
{
}
template <class T, class ... Ts>
void f(const T& a, const Ts&... args)
{
std::cout << a;
f(args...);
}
Run Code Online (Sandbox Code Playgroud)
几乎像真实的东西:-)
#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);
}
Run Code Online (Sandbox Code Playgroud)