【发布时间】:2020-04-26 09:30:26
【问题描述】:
我正在尝试编写一个函数,该函数为所有非枚举类型实现一般行为,为所有枚举类型实现一般行为,然后能够通过完全专门化来专门化某些类型的特定行为功能。到目前为止,这是我的代码:
// Func.h
#include <cstdio>
#include <type_traits>
template <typename T, std::enable_if_t<!std::is_enum<T>{}>* = nullptr >
void Func()
{
printf("General case\n");
}
template <typename T, std::enable_if_t<std::is_enum<T>{}>* = nullptr >
void Func()
{
printf("enum\n");
}
template <>
void Func<bool>()
{
printf("bool\n");
}
// main.cpp
#include <Func.h>
enum Enum
{
A,
B
};
int main()
{
Func<float>();
Func<Enum>();
Func<bool>();
}
它无法编译,我真的不知道如何正确处理。如果我让专门的原型在上面的代码中,我得到这个链接错误:
error LNK2005: "void __cdecl Func<bool,0>(void)" (??$Func@_N$0A@@@YAXXZ) already defined in main.obj
如果我制作专用原型 template<> void Func<bool, nullptr>(),我会收到以下编译错误:
error C2912: explicit specialization 'void Func<bool,nullptr>(void)' is not a specialization of a function template
这些测试是使用带有 c++14 标准的 Visual Studio 2015 编译器完成的
我不知道从哪里开始,任何帮助将不胜感激
【问题讨论】:
-
Visual Studio 2015 编译器使用 C++14 标准。我编辑了问题以添加此信息
标签: c++ templates enums template-specialization