我有以下取自现代 C++ 设计的代码。当我使用它时,我得到了编译错误,我认为无效的 sizeof 操作数。任何人都可以指出是什么问题。谢谢!
template<bool>
struct CompileTimeChecker {
CompileTimeChecker(...);
};
template<>
struct CompileTimeChecker<false> {
};
#define STATIC_CHECK(expr, msg) \
{\
class ERROR_##msg {}; \
(void)sizeof(CompileTimeChecker<(expr) != 0>((ERROR_##msg())));\
}
template <class To, class From>
To safe_reinterpret_cast(From from) {
STATIC_CHECK(sizeof(From) <= sizeof(To), Destination_Type_Too_Narrow);
return reinterpret_cast<To>(from);
}
int main(void)
{
int a[20];
void* somePointer = a;
char c = safe_reinterpret_cast<int>(somePointer);
}
错误:
d:\technical\c++study\readparsing\readparsing\addressconv.cpp(29) : 错误 C2066: 转换为函数类型是非法的 1> d:\technical\c++study\readparsing\readparsing\addressconv.cpp( 37) : 请参阅正在编译的函数模板实例化 'To safe_reinterpret_cast(From)' 1> 使用 1> [ 1> To=int, 1> From=void * 1> ] 1>d:\technical\c++study \readparsing\readparsing\addressconv.cpp(29) : 错误 C2070: 'CompileTimeChecker<__formal> (safe_reinterpret_cast::ERROR_Destination_Type_Too_Narrow (__cdecl *)(void))': 非法 sizeof 操作数 1> with 1> [ 1> __formal=true 1 > ]