我想创建以下类,但编译器给出错误(它告诉我们方法的签名是相同的):
struct entities_set_less
{
constexpr bool operator()(const ContentEntity*& _Left, const ContentEntity*& _Right) const
{ // apply operator< to operands
return (_Left < _Right);
}
constexpr bool operator()( const const ContentEntity*& _Left, const const ContentEntity*&_Right) const
{ // apply operator< to operands
return (_Left < _Right);
}
};
从我的角度来看,像 const const ContentEntity*&
这样的表达式意味着“对 const ContentEntity 上的指针的 const 引用”。它应该与 const ContentEntity*&
不同,后者只是“对非 const 类型上的指针的 const 引用”。
最佳答案
首先,让我们澄清(或尝试)您真正想要的是什么。你说你想要一个“const引用”……但无论如何,引用(实际上)是const(即,一旦引用变量绑定(bind)到其目标,它随后就不能绑定(bind)到不同的目标)。
因此,您的意思可能是希望第二个重载中的参数是对指向常量对象的常量指针的引用;也就是说,指针和对象都不能修改(在第一次重载中,指向的对象不能修改,但引用的指针可以。
要使指针const
,您需要在指针指示符(*
)之后添加该关键字。像这样:
struct entities_set_less {
constexpr bool operator()(const ContentEntity*& _left, const ContentEntity*& _light) const
{ // references to non-const pointers to const objects
return (_left < _light);
}
constexpr bool operator()(const ContentEntity* const& _left, const ContentEntity* const& _right) const
{ // references to CONST pointers to const objects
return (_left < _right);
}
};
请注意,我还将您的 _Left
和 _Right
标识符更改为 _left
和 _right
,因为 ID 开头下划线后跟大写字母的被保留。来自 this C++17 Draft Standard :
5.10 Identifiers [lex.name]
…
(3.1) — Each identifier that contains a double underscore__
or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use.
关于c++ - 如何创建对 const 指针的 const 引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72261075/