How to properly use references with variadic templates

前端 未结 3 1328
你的背包
你的背包 2021-02-04 08:06

I have something like the following code:

   template
   void inc(T1& t1, T2& t2, T3& t3, T         


        
3条回答
  •  北海茫月
    2021-02-04 08:23

    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
    inline void inc_impl(T& t, U&...u) { ++t; inc_impl(u...); }
    
    template
    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.

提交回复
热议问题