How to properly use references with variadic templates

*爱你&永不变心* 提交于 2019-12-03 02:19:13

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...); }

Should I be using r-values instead of references?

You mean rvalue references? No, I see no reason for those.

Possible hints or clues as to how to accomplish what I want correctly.

You're already there. Your code should do what you want.

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?)

The C++ standard doesn't guarantee any inlining. You could check out what the compiler generates. If you want everything to be inlined -- including the upmost inc-call -- you could put an inline to both of the functions as a request. If you want something like your non-variadic template, you could wrap it like this:

inline void inc_impl() {}

template<typename T, typename...U>
inline void inc_impl(T& t, U&...u) { ++t; inc_impl(u...); }

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

Now inc is not inline while each of its implementations will probably contain no real function calls when the inlining of inc_impl calls are done -- but again, there's no guarantee.

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?)

The standard won't guarantee an optimization will be performed, it only specifies the behavior and the result. Whether the function will be inlined problem of the implementation.

In fact, the inline keyword is only a hint to the compiler which is often ignored because the compiler can decide better.

Finally, g++-4.5 completely inlined all inc functions at -O2. Don't know if it's what you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!