如何使转换运算符返回引用和非引用

How to make conversion operator returning reference and non reference

本文关键字:引用 返回 运算符 何使 转换      更新时间:2023-10-16

我有一个模板类,看起来像:

template<class T>
class A
{
  public:
     operator T() const {  return value;}
     operator T&() { return value;}
  private:
       T value;
}

似乎从未调用运算符 T() 常量。即使在这样的声明中

const int a = myA;

其中 myA 是 A 的实例。上面的代码有问题吗?

仅当您定义类型为 const A<T> 的对象时,运算符才会生效。例如:

const A<int> myA;
int someInt = myA;

会打电话给operator T() const.

而且,正如本杰明·林德利指出的那样,如果你通过const引用访问对象,这当然是正确的。