具有未知数量参数的C ++模板函数

编程入门 行业动态 更新时间:2024-10-22 12:36:15
本文介绍了具有未知数量参数的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 ++模板函数

本文发布于:2023-10-27 11:27:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533220.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   数量   模板   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!