将const转换为非const或将const转换为const [英] `const` to non-`const` or non-`const` to `const`
问题描述
当同时存在 const
和非 const
吸气剂时,以下代码用于减少代码重复.它从非 const
创建 const
版本.我对此进行了搜索,很多人说我应该改为从 const
创建非 const
版本.
The code below is used for reducing code duplication when there are both const
and non-const
getters. It creates the const
version from non-const
. I searched about this a bit and a lot of people are saying that I should instead create the non-const
version from const
.
我的想法是,如果我从 const
版本创建非 const
版本,与下面的代码相反,则取消引用返回的指针或最初是 const
的引用.我真的不确定这一点,所以我要澄清一下,什么是正确的方向"?
My thought is that if I create the non-const
version from the const
version, opposite from the code below, it may be unsafe to dereference the returned pointer or reference which was originally const
. I'm really not sure about this, so I'm asking for clarification, and what is the correct 'direction'?
template<typename T>
struct Constifier
{
typedef T Type;
};
template<typename T>
struct Constifier<T &>
{
typedef const T &Type;
};
template<typename T>
struct Constifier<T &&>
{
typedef const T &&Type;
};
template<typename T>
struct Constifier<T *>
{
typedef const T *Type;
};
template<typename F>
struct ReturnType;
template<typename R, typename ...Ts>
struct ReturnType<R (*)(Ts ...ts)>
{
typedef R Type;
};
template<typename R, typename T, typename ...Ts>
struct ReturnType<R (T::*)(Ts ...ts)>
{
typedef R Type;
};
template<typename T, typename F, typename ...Ts>
auto callConstVersion(const T *t, F f, Ts ...ts)
{
return const_cast<typename Constifier<typename ReturnType<F>::Type>::Type>((const_cast<T *>(t)->*f)(ts...));
}
struct A
{
A *p;
A *get() {return p;}
const A *get() const {return callConstVersion(this, static_cast<A *(A::*)()>(&A::get));}
};
推荐答案
您应始终从 const
创建一个 non-const
版本,而不要相反.解释很简单,请这样想:
You should always create non-const
version from const
one and not in the opposit way. The explanation is simple, think of it this way:
您只能在 non-const
对象上调用 non-const
getter.如果对象是 non-const
,则可以在 non-const
方法内安全地 const_cast
您的 const
吸气剂.为什么?因为您只能在 non-const
对象上调用此方法.
You can call non-const
getter only on the non-const
object. If the object is non-const
, you can safely const_cast
your const
getter inside the non-const
method. Why? Because you can only call this method on non-const
object.
进行相反的操作并不真正安全,因为在 const
中调用 non-const
方法时,您不能保证保持不变.
Doing the opposit is not really safe, because when calling non-const
method in the const
one you cannot assure, that constness is preserved.
这篇关于将const转换为非const或将const转换为const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!