reinterpret_cast 一个模板 class 到 const 版本
reinterpret_cast a template class to const version
据我所知,带有模板参数 <Type>
的模板 class 与 <const Type>
.
完全不同
template<typename T>
struct Wrapper
{
T obj = T{};
//other code
};
现在我无法将 Wrapper<int>&
传递给需要 Wrapper<const int>&
的函数。
void someFunc(Wrapper<const int>& wrapper);
//...
Wrapper<int> wrapper;
someFunc(wrapper); //error
reinterpret_cast
将其转换为 const 版本会出现什么问题?
operator Wrapper<const T>&() { return *(reinterpret_cast<Wrapper<const T>*>(this)); }
将以上行添加到 Wrapper
使其无需创建新的 <const int>
对象即可工作。 obj
无法在函数内部访问,因此传递的参数实际上是 <const Type>
还是 <Type>
.
应该无关紧要
如果没有模板专业化,这里会出现什么问题吗(就标准与实践而言)?
在 const 和非 const 情况下有许多不同的优化,这意味着 class 的内存布局(例如,因为 const 对象不需要实际存在)和class 的用法可能不同。
换句话说:为此使用 reinterpret_cast 会导致意外行为,不应这样做。
在我看来,过分使用 const
关键字会导致代码更复杂而没有任何好处,这就是其中之一。
我建议避免 <const Type>
情况而不是尝试处理它们。
在不知道用例的情况下,在我看来大多数用例都可以通过使用 const Wrapper<T>
而不是 Wrapper<const T>
来涵盖。
据我所知,带有模板参数 <Type>
的模板 class 与 <const Type>
.
template<typename T>
struct Wrapper
{
T obj = T{};
//other code
};
现在我无法将 Wrapper<int>&
传递给需要 Wrapper<const int>&
的函数。
void someFunc(Wrapper<const int>& wrapper);
//...
Wrapper<int> wrapper;
someFunc(wrapper); //error
reinterpret_cast
将其转换为 const 版本会出现什么问题?
operator Wrapper<const T>&() { return *(reinterpret_cast<Wrapper<const T>*>(this)); }
将以上行添加到 Wrapper
使其无需创建新的 <const int>
对象即可工作。 obj
无法在函数内部访问,因此传递的参数实际上是 <const Type>
还是 <Type>
.
如果没有模板专业化,这里会出现什么问题吗(就标准与实践而言)?
在 const 和非 const 情况下有许多不同的优化,这意味着 class 的内存布局(例如,因为 const 对象不需要实际存在)和class 的用法可能不同。
换句话说:为此使用 reinterpret_cast 会导致意外行为,不应这样做。
在我看来,过分使用 const
关键字会导致代码更复杂而没有任何好处,这就是其中之一。
我建议避免 <const Type>
情况而不是尝试处理它们。
在不知道用例的情况下,在我看来大多数用例都可以通过使用 const Wrapper<T>
而不是 Wrapper<const T>
来涵盖。