当调用来自同一个重载的非常量版本成员函数时,可以删除常量限定符吗
Is it okay to remove const qualifier when the call is from the same non-const version overloaded member function?
例如:
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);
}
};
问题是,我希望避免在常量findB和非常量findB成员函数中重复相同的逻辑。
是的,您可以将对象强制转换为const
,调用const
版本,然后将结果强制转换为非const
:
return const_cast<B&>(static_cast<const A*>(this)->findB());
只有当所讨论的对象最初不是声明为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;
};
一般来说,我的成员职能很短,所以重复是可以容忍的。有时,您可以将实现因素化为一个私有模板成员函数,并从两个版本调用该函数。
我认为,在这里使用强制转换是可以的,但如果你确实想避免它,你可以使用一些模板魔法:
struct B
{
B(const B&)
{
std::cout << "oops I copied";
}
B(){}
};
struct A {
public:
A(){}
A(const A&){ std::cout << "a is copied:(n";}
const B& findB() const { return getter(*this); }
B& findB() { return getter(*this); }
private:
template <typename T, typename V>
struct same_const
{
typedef V& type;
};
template <typename T, typename V>
struct same_const<const T, V>
{
typedef const V& type;
};
template <typename T>
static typename same_const<T,B>::type getter(T& t) { return t.b;}
B b;
};
int main()
{
A a;
const A a_const;
const B& b1 = a.findB();
B& b2 = a.findB();
const B& b3 = a_const.findB();
//B& b4 = a_const.findB();
}
相关文章:
- 从 Typedef 数据类型中删除常量
- 为什么const_cast删除指针的恒常性,而不删除指向常量的指针的恒常性?
- 从嵌套模板中删除常量
- 防止将临时传递为常量引用的方法,该方法比删除 r 值重载更好地缩放
- 不能只删除方法的常量重载?
- std::remove_pointer 无法删除 VS2012 上的常量易失性函数指针
- 当调用来自同一个重载的非常量版本成员函数时,可以删除常量限定符吗
- 从函数返回类型中删除常量是否会中断 ABI
- 如何从'char const*'中删除常量
- 模板引用折叠正在删除常量引用返回类型的cv限定符
- 如何删除类型名中每个元素的常量引用修饰符.T.
- 类成员有自己的常量成员,因此构造函数被隐式删除
- C++无法在递归中删除对象的常量
- 全局静态常量shared_ptr被另一个shared_ptr的析构函数奇怪地窃取和删除,为什么?
- 如果模板参数是指针,则在 getter 上删除了常量限定符
- 如何在 c++ 中删除常量数组
- 类型为 std::String&- 的非常量引用的初始化无效 - 如何删除
- 错误:在此处声明unique_ptr(常量 unique_ptr&) = 删除;
- 为什么在 C++11 中删除了对逗号运算符在常量表达式中的限制
- DirectX11如何从常量缓冲区中删除未使用的变量