我正在尝试编写一个函数,该函数为所有非枚举类型实现一般行为,为所有枚举类型实现一般行为,然后能够通过完全专门化函数来专门化某些类型的特定行为。到目前为止,这是我的代码:
// 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>();
}
它无法编译,我真的不知道如何正确处理。如果我像上面的代码一样让专用原型(prototype),我得到这个链接错误:
error LNK2005: "void __cdecl Func<bool,0>(void)" (??$Func@_N$0A@@@YAXXZ) already defined in main.obj
如果我制作专用原型(prototype)
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 编译器完成的
我不知道从哪里开始,任何帮助将不胜感激
最佳答案
您收到链接错误,因为 Func<bool>()
在包含在多个编译单元中的头文件中定义。解决方法很简单:把 inline
之前 void Func<bool>()
:
template<>
inline void Func<bool>()
{
// ...
}
函数模板隐含
inline
, 但函数和显式模板特化 are not .如果它们在头文件中定义,则应标记为 inline
.
关于c++ - 带有 std::if_enabled_t 参数的模板函数的完全特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61438535/