【问题标题】:is there a sense of calling std::forward on this object in method call (as opposite to arguments)?是否有在方法调用中在此对象上调用 std::forward 的感觉(与参数相反)?
【发布时间】:2023-02-20 20:27:06
【问题描述】:

我想知道std::forward在这里是否有意义。

template <class T>
void juju(T && x) {
  std::forward<T>(x).jaja();
}

我猜它没有任何意义,因为this 在方法调用中始终是一个指针,所以它是由右值或左值引用构成的没有区别。但请确认我的直觉或解释为什么我错了。

上面的例子是一个简化的method from this codejujufor_eachTExecutionPolicyjajaget_devices

【问题讨论】:

  • 成员函数可以对左值和右值引用有不同的重载。

标签: c++ perfect-forwarding


【解决方案1】:

当你在方法中考虑 this 时,你就快了。在调用成员方法之前有重载决议。左值和右值引用可以有不同的重载:

#include <utility>
#include <iostream>


template <class T>
void juju(T && x) {
  std::forward<T>(x).jaja();
}

struct foo {
    void jaja() & { std::cout << "hello
";}
    void jaja() && { std::cout << "&&
";}
};

int main(){
    juju(foo{});
    foo f;
    juju(f);
}

Output:

&&
hello

【讨论】:

    猜你喜欢
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2017-06-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    相关资源
    最近更新 更多