dch*_*tri 6 c++ user-interface const
例如:
struct B{};
struct A {
const B& findB() const { /* some non trivial code */ }
// B& findB() { /* the same non trivial code */ }
B& findB() {
const A& a = *this;
const B& b = a.findB();
return const_cast<B&>(b);
}
};
Run Code Online (Sandbox Code Playgroud)
问题是我想避免在常量findB和非常量findB成员函数中重复相同的逻辑.
是的,您可以将对象强制转换为const,调用const版本,然后将结果转换为非const:
return const_cast<B&>(static_cast<const A*>(this)->findB());
Run Code Online (Sandbox Code Playgroud)
const只有在最初没有声明有问题的对象时,才能安全地抛弃const.由于您处于非const成员函数中,因此您可以知道这种情况,但这取决于实现.考虑:
class A {
public:
A(int value) : value(value) {}
// Safe: const int -> const int&
const int& get() const {
return value;
}
// Clearly unsafe: const int -> int&
int& get() {
return const_cast<int&>(static_cast<const A*>(this)->get());
}
private:
const int value;
};
Run Code Online (Sandbox Code Playgroud)
一般来说,我的会员职能很短,所以重复是可以容忍的.您有时可以将实现分解为私有模板成员函数,并从两个版本调用它.