右值引用不匹配

AKM*_*AKM -1 c++ assert pass-by-reference rvalue-reference

我有这个练习,其中我们使用模板类尝试右值和左值引用的各种组合,我收到两个断言错误;如果有人可以指导的话。

#include <assert.h>

typedef int& IntLRef;
typedef IntLRef& IntLLRef;
typedef IntLRef&& IntLRRef;

typedef int&& IntRRef;
typedef IntRRef& IntRLRef;
typedef IntRRef&& IntRRRef;

template<typename T, typename U>
struct IsSameType
{
  static const bool value = false;
};

template<typename T>
struct IsSameType <T, T>
{
    static const bool value = true;
};
static_assert(IsSameType<IntLRef, IntLLRef>::value, "LRef DIF LLRef"); static_assert(IsSameType<IntLRef, IntLRRef>::value, "LRef DIF LRRef"); static_assert(IsSameType<IntLLRef, IntLRRef>::value, "LLRef DIF LRRef");

static_assert(IsSameType<IntRRef, IntRLRef>::value, "RRef DIF RLRef"); static_assert(IsSameType<IntRRef, IntRRRef>::value, "RRef DIF RRRef"); static_assert(IsSameType<IntRLRef, IntRRRef>::value, "RLRef DIF RRRef");

int main();
Run Code Online (Sandbox Code Playgroud)

我收到断言错误:

rvalue_ex3.cpp:34:48: error: static assertion failed: RRef DIF RLRef
   34 |   static_assert(IsSameType<IntRRef, IntRLRef>::value, "RRef DIF RLRef");
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
rvalue_ex3.cpp:36:49: error: static assertion failed: RLRef DIF RRRef
   36 |   static_assert(IsSameType<IntRLRef, IntRRRef>::value, "RLRef DIF RRRef");
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
akm009@a
Run Code Online (Sandbox Code Playgroud)

我需要进行修改以断言它是正确的并理解它失败的原因

bit*_*ask 5

这称为引用折叠

允许通过模板或 typedef 中的类型操作形成对引用的引用,在这种情况下,引用折叠规则适用:右值引用对右值引用折叠为右值引用,所有其他组合形成左值引用

(强调已添加)

这意味着IntRRefwhich isint&&不一样,IntRLRef因为后者被定义为IntRRef&which 是对右值引用的左值引用,因此折叠为左值引用:int&