具有未知数量参数的C ++模板函数 [英] C++ template function with unknown number of arguments

查看:97
本文介绍了具有未知数量参数的C ++模板函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个无用的问题,但它卡在我的头脑几个小时。

this is probably a useless problem but it stuck on my mind for few hours.

我想写一个函数,接受一些(POD)参数,字符串并返回连接。例如

I wanna write a function which accepts some (POD) arguments, convert them to string and return the concatenation. for example

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

很容易,
,但是当我想用未知参数编写相同的函数时,它会变得很难(对我来说)。

pretty easy, huh? but it get pretty tough (for me of course) when I wanna write the same function with unknown number of arguments.

是甚至可能吗?任何解决方案?

is it even possible? any solution?

推荐答案

几乎像真实的东西: - )

Almost like the 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);
}

这篇关于具有未知数量参数的C ++模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆