【发布时间】:2021-07-12 02:13:34
【问题描述】:
AFAIK,带有模板参数<Type> 的模板类与<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'ing 到它的 const 版本会出现什么问题?
operator Wrapper<const T>&() { return *(reinterpret_cast<Wrapper<const T>*>(this)); }
将上述行添加到Wrapper 使其无需创建新的<const int> 对象即可工作。 obj 不能在函数内部访问,所以传递的参数实际上是<const Type> 还是<Type> 应该没有关系。
如果没有模板专业化,这里有什么问题吗(就标准与实践而言)?
【问题讨论】:
标签: c++ templates constants reinterpret-cast