const转换为非const或非const转换为const
`const` to non-`const` or non-`const` to `const`
当同时存在const
和非const
getter时,下面的代码用于减少代码重复。它从非const
创建const
版本。我搜索了一下,很多人都说我应该从const
创建一个非const
版本。
我的想法是,如果我从const
版本创建非const
版本,与下面的代码相反,解引用返回的指针或引用最初是const
可能是不安全的。我真的不确定,所以我要求澄清一下,什么是正确的"方向"?
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
版本,而不是相反。解释很简单,可以这样想:
只能在non-const
对象上调用non-const
getter。如果对象是non-const
,你可以安全地在non-const
方法中const_cast
你的const
getter。为什么?因为你只能在non-const
对象上调用这个方法。
做相反的事情是不安全的,因为当在const
中调用non-const
方法时,你不能保证constness是保留的。
相关文章:
- 将 const 转换为 const char* 无效,我该如何解决?使用 gcc7 时失败
- "class<T>"到"class<const T>"转换运算符的惯用方法
- 编译器可以静默地从 const 转换为 const 和,反之亦然吗?
- 从 Object<const T> 转换为 Object<t>
- 为什么在设置类成员时会自动从 const 转换为 non-const 并发生?
- 同时向下投递并从 const 转换为非 const
- 没有匹配的操作数[template]/无法从Type const*转换为Type
- static const转换为c++共享库中的对象.是进程间共享的吗?
- 无法从 *const 转换为 &in += 运算符
- C2664 无法在 Qt C++ 中将参数 1 从用户 *const 转换为用户
- const转换操作符
- std::pair中的Const转换
- const转换为非const或非const转换为const
- C++11:无法将参数从'T *const'转换为'T *&&'
- Const转换std容器
- 复制构造函数将const转换为非const
- 在c++中将非const转换为const
- 无法将参数 1 从 'PrintVisitor *const ' 转换为 'Visirot &'
- 将const T* const转换为T*
- 操作符情况下的c++ const转换