【问题标题】:reference collapsing with template template class与模板模板类的引用折叠
【发布时间】:2013-07-15 19:44:46
【问题描述】:

为什么引用折叠不适用于

template<typename T, template<typename> class C>
void f(C<T> && x); // x declaration is an rvalue!

如何完善前向以及如何避免 const lvalue ref、lvalue ref、rvalue ref in 的所有组合重载

template<typename T> // not necessary a template template class here
void f(C<T>, C<T>, C<T>, ..., C<T>)
{
    // do something with T
    // move or copy arguments to a function
}

【问题讨论】:

  • 引用折叠仅在表单为T&amp;&amp; 时适用。 C&lt;T&gt;&amp;&amp; 总是指定一个右值引用(如std::vector&lt;T&gt;&amp;&amp;
  • @AndyProwl:或者当表单是auto &amp;&amp;
  • @a.lasram:如果您需要完美转发,请将表单设为 template&lt;typename U&gt; f(U&amp;&amp;) 并添加一个 SFINAE 约束,说明对于某些 TU 必须是 C&lt;T&gt; 的实例化。
  • @a.lasram:因为我必须详细说明它才能使它成为一个体面的答案,而且我现在没有时间:(
  • 这真是一团糟。该死的 C++11。

标签: c++ templates c++11 rvalue-reference


【解决方案1】:

不幸的是,您将需要使用某种 SFINAE

template<typename T>
struct HasOneTypeParam : std::false_type { };

template<typename T, template<typename> class C>
struct HasOneTypeParam<C<T>> : std::true_type { };

template<typename ...T>
struct SlurpThemAll { typedef int type; };

template<typename ...T, 
  typename SlurpThemAll<
     bool[HasOneTypeParam<typename std::decay<T>::type>::value * 2 - 1]...
     >::type = 0>
void f(T &&... x);

根据您实际想要做的事情,您可以要求所有 std::decay&lt;T&gt;::type 为同一类型,并添加更多 SFINAE hack。

【讨论】:

    猜你喜欢
    • 2014-02-07
    • 2011-08-27
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多