很久以前(去年1月)我为我的游戏引擎制作了一个类型不可知的日志记录系统。 C ++ 17发生了,我能够用if constexpr
替换大量复杂的lambda逻辑,使整个事情更容易阅读,并且通常更好。记录器中的类型检查结构如下:
if constexpr (std::is_[type]<loggableType>{})
{
// Type-specific text here...
}
所以我有一个很大的if / else-if / else塔,它应该为每个支持的type-trait生成正确的结果(std :: is_arithmetic,std :: is_union,std :: is_class,std :: is_pointer,std :: is_member_function_pointer和std :: is_enum)。
我发现编译器错误的原因是枚举,联合,结构和类漏洞对std::is_member_function_pointer
的影响。这是一个MSVC错误还是我错过了什么?
希望这会复制该问题(请参阅我的源代码的旧版本):
#include <type_traits>
#include <iostream>
template<typename loggableType>
int TraitTest(loggableType dataLogging)
{
if constexpr(std::is_arithmetic<loggableType>{})
{
return 0;
}
else if constexpr (std::is_union<loggableType>{})
{
return 1;
}
else if constexpr (std::is_class<loggableType>{})
{
return 2;
}
else if constexpr (std::is_pointer<loggableType>{})
{
return 3;
}
else if constexpr (std::is_member_function_pointer<loggableType>{})
{
std::cout << dataLogging;
return 4;
}
else if constexpr (std::is_enum<loggableType>{})
{
return 5;
}
}
class Chicken
{
public:
void Squawk() { std::cout << "Squawk?"; }
};
int main()
{
class testClass { };
testClass tstClass;
struct testStruct { };
testStruct tstStruct;
union testUnion { };
testUnion tstUnion;
enum class TEST_ENUM_VALS { VAL_0, VAL_1 };
Chicken testChicken = Chicken();
int result0 = TraitTest(tstStruct);
int result1 = TraitTest(tstClass);
int result2 = TraitTest(tstUnion);
int result3 = TraitTest(TEST_ENUM_VALS::VAL_0);
return 0;
}