为什么不能给 const 仿函数返回的引用赋值?
#include <vector>
template<typename T>
class Test {
public:
T & operator()(size_t index) const {
return A[index];
}
private:
std::vector<T> A{1,2,3};
};
int main() {
const Test<double> test1;
const Test<double> test2;
Test<double> test;
test(0) = test1(0) + test2(1);
}
我得到下面的编译错误,但我不明白为什么仿函数的 const 禁止赋值,因为仿函数本身没有改变它的对象。
main.cpp:7:12: error: binding value of type 'const
__gnu_cxx::__alloc_traits<std::allocator<double> >::value_type' (aka 'const double') to
reference to type 'double' drops 'const' qualifier
return A[index];
^~~~~~~~
main.cpp:19:7: note: in instantiation of member function 'Test<double>::operator()' requested
here
test(0) = test1(0) + test2(1);
^
如果仿函数不是 const 我会得到一个编译错误因为 const Test<double> test1
,但这对我来说很清楚。
我怎样才能让上面的代码运行?我需要使用仿函数从 const 对象分配值。
最佳答案
this
在该方法的上下文中是 Test<double> const *
这意味着 this->A
隐式为 const
.因此,A[index]
类型为 double const &
无法转换为 T &
(即 double &
)。
换句话说,const
的实例成员对象本身 const
(除非它们被声明为 mutable
)。
正确的解决方案是有两个 operator()
实现,一个 const
一个不是:
T & operator()(size_t index) { return A[index]; }
T const & operator()(size_t index) const { return A[index]; }
前者将在非 const 实例上调用并且确实允许赋值;后者将在 const 实例上调用,不允许赋值。
( Demo )
关于c++ - 返回 T 引用的 Const 仿函数禁止赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58401385/