【发布时间】:2015-07-28 10:35:16
【问题描述】:
我正在尝试替换一个类型,typedef'ed 从内置整数类型,用于具有自定义类的大型项目,这将实现一些额外的功能,如避免截断分配等。但是项目广泛使用reinterpret_cast<void*>(value) 之类的转换。我在我的新班级中实现了operator void*() 的天真尝试,但显然这不能实现reinterpret_cast,只允许static_cast 到void*。代码如下:
#include <cstdlib>
#include <type_traits>
#define USE_NEW_VALUE_TYPE
#ifdef USE_NEW_VALUE_TYPE
struct Value
{
size_t value;
operator void* () { return reinterpret_cast<void*>(value); }
};
static_assert(std::is_pod<Value>::value,"Value is not POD");
#else
typedef size_t Value;
#endif
int main()
{
Value v{5};
void* p=reinterpret_cast<void*>(v); // This is how the project uses it
}
我认为如果课程是 POD,这将允许我执行 reinterpret_cast 之类的操作。但是这段代码给了我一个编译错误:
从“Value”类型到“void*”类型的无效转换
那么我的问题是:如何添加对这种reinterpret_cast 的支持,这样我就不必在项目的每个部分手动将其切换为static_cast?
【问题讨论】:
标签: c++ reinterpret-cast