小编3l4*_*l4x的帖子

为什么我的代码打印两次右值而不是右值和左值?

因此,我想练习的用法,std::forward并创建了Test具有2个构造函数的类。1个带T&,另一个带T&&作为过载。T&打印左值,并T&&打印右值,所以我知道正在使用哪个构造函数。我在堆栈上创建了2个类的实例,令我惊讶的是,这两个实例都使用了T&&重载。

#include <iostream>
#include <type_traits>
#include <utility>

template <class T> auto forward(T &&t) {
  if constexpr (std::is_lvalue_reference<T>::value) {
    return t;
  }
  return std::move(t);
}

template <class T> class Test {
public:
  Test(T &) { std::cout << "lvalue" << std::endl; };
  Test(T &&) { std::cout << "rvalue" << std::endl; };
};

int main() {
  int x = 5;
  Test<int> a(forward(3));
  Test<int> b(forward(x));
  return …
Run Code Online (Sandbox Code Playgroud)

c++ forward rvalue lvalue stdmove

10
推荐指数
1
解决办法
194
查看次数

标签 统计

c++ ×1

forward ×1

lvalue ×1

rvalue ×1

stdmove ×1