14

我有类似以下代码的内容:

   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 的示例,这里的区别似乎是引用的使用。我想出了以下几点:

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 值而不是引用吗?

  • 关于如何正确完成我想要的可能的提示或线索。

  • 关于递归函数调用的问题,新提议的标准提供了哪些保证,是否有迹象表明上述可变参数版本将与原始版本一样最佳?(我应该添加内联或类似的吗?)

4

3 回答 3

13

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

inc(1);

所以,我会坚持使用常规参考:

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

template<typename T,typename ... Args>
void inc(T& t, Args& ... args) { ++t; inc(args...); }
于 2010-04-11T05:32:27.887 回答
2

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

你的意思是右值引用?不,我认为没有理由。

关于如何正确完成我想要的可能的提示或线索。

你已经在那里了。你的代码应该做你想做的事。

新提议的标准对递归函数调用的问题提供了什么保证,是否有迹象表明上述可变参数版本将与原始版本一样最佳?(我应该添加内联或类似的吗?)

C++ 标准不保证任何内联。您可以查看编译器生成的内容。如果您希望所有内容都被内联 - 包括最上面的 inc 调用 - 您可以将内联两个函数作为request。如果你想要类似非可变模板的东西,你可以像这样包装它:

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

现在 inc 不是内联的,而当 inc_impl 调用的内联完成时,它的每个实现都可能不包含真正的函数调用——但同样不能保证。

于 2010-04-11T05:49:46.690 回答
1

新提议的标准对递归函数调用的问题提供了什么保证,是否有迹象表明上述可变参数版本将与原始版本一样最佳?(我应该添加内联或类似的吗?)

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.

于 2010-04-11T05:52:16.637 回答