右值引用不匹配



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

#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();

我收到断言错误:

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

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

这称为引用折叠:

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

(着重号后加)

这意味着int&&IntRRefIntRLRef不同,因为后者被定义为IntRRef&,它是对右值引用的左值引用,因此折叠为左值引用:int&

最新更新