【问题标题】:How to use std::forward in a template method, when only one element of, for example std::array<std::array>, is passed to another template method如何在模板方法中使用 std::forward,例如 std::array<std::array> 的一个元素被传递给另一个模板方法
【发布时间】:2020-04-04 22:15:33
【问题描述】:

假设我们有以下简化的场景,其中模板化方法调用模板化方法如下:

template<typename Ta>
inline auto fa(Ta&& ta){  
myclassA ra;
// doing things to "ra" based on "ta"...
return ra
}

template<typename Tb>
inline auto fb(Tb&& tb){  
myclassB rb;
// doing things to "rb" based on "tb"...
// at some point:
auto temp = fa(tb[n][m]) //should this not be std::forward? how do you do that? 
// doing things to "rb" based on "temp"...
return rb;
}

有了通用引用,我知道我应该std::forward。如果我需要整体传递tb,那么我会做auto temp = fa(std::forward&lt;Tb&gt;(tb))。但是我不清楚如何通过tb[n][m],因为我只通过了tb 的一个条目(一个条目)。他们有办法进行这种转发吗?

【问题讨论】:

  • 看起来您正在制作元素的本地副本。故意的?
  • @ZuodianHu 你的意思是auto temp = fa(tb[n][m])那一行吗?
  • 没关系,你将它传递给函数。

标签: c++ templates forwarding-reference


【解决方案1】:

假设您没有尝试对异常做任何事情,您可以转发参数并在转发参数上调用operator[]。将选择正确的成员函数重载。

auto temp = fa( std::forward<Tb>( tb )[n][m] );

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2012-12-08
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多