如何正确使用参数与可变参数模板 [英] How to properly use references with variadic templates

查看:135
本文介绍了如何正确使用参数与可变参数模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似下面的代码:

   template<typename T1, typename T2, typename T3, typename T4>
   void inc(T1& t1, T2& t2, T3& t3, T4& t4) { ++t1; ++t2; ++t3; ++t4; }

   template<typename T1, typename T2, typename T3>
   void inc(T1& t1, T2& t2, T3& t3) { ++t1; ++t2; ++t3; }

   template<typename T1, typename T2>
   void inc(T1& t1, T2& t2) { ++t1; ++t2; }

   template<typename T1>
   void inc(T1& t1) { ++t1; }



我想使用即将推出的标准中提出的可变参数模板重新实现它。然而,我所见到的所有例子,到目前为止在线似乎是printf类似的例子,这里的区别似乎是使用引用。我想出了以下:

I'd like to reimplement it using the proposed variadic templates from the upcoming standard. However all the examples I've seen so far online seem to be printf like examples, the difference here seems to be the use of references. I've come up with the following:

inline void inc() { }

template<typename T>
inline void inc(T&& t) { ++t; }

template<typename T,typename ... Args>
inline void inc(T&& t, Args&& ... args) { ++t; inc(args...); }

我想知道的是:


  • 我应该使用r值而不是引用吗?

  • Should I be using r-values instead of references?

可能的提示或线索

新建议的标准提供了什么保证来解决递归函数调用的问题,是否有一些迹象表明上述变量版本会与原来一样最佳吗? (应该添加内联还是某些?)

What guarantees does the new proposed standard provide wrt the issue of the recursive function calls, is there some indication that the above variadic version will be as optimal as the original? (should I add inline or some-such?)

推荐答案

在这里不使用右值引用,因为这将允许你绑定到可以允许这样无意义代码的右值:

I would not use rvalue references here, because that will allow you to bind to rvalues which can allow such nonsensical code as:

inc(1);

所以,我会坚持使用定期参考:

So, I would stick with regular references:

template<typename T>
void inc(T& t) { ++t; }

template<typename T,typename ... Args>
void inc(T& t, Args& ... args) { ++t; inc(args...); }

这篇关于如何正确使用参数与可变参数模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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