枚举的模板专业化

nil*_*ton 8 c++ enums templates template-specialization

是否有可能专门为枚举的模板化方法?

像(下面的无效代码):

template <typename T>
void f(T value);

template <>
void f<enum T>(T value);
Run Code Online (Sandbox Code Playgroud)

在这种情况下这是不可能的,那么假如我有专业化的多种类型,如int,unsigned int,long long,unsigned long long,等等,那么其专业化的枚举值将使用?

Jam*_*lis 21

您可以使用std::enable_ifstd::is_enum来自<type_traits>做到这一点.

在对我的一个问题的回答中,litb发布了一个非常详细和精心编写的解释,说明如何使用Boost等价物完成此操作.


Tho*_*thy 7

我不确定我是否正确理解了您的问题,但您可以在特定枚举上实例化模板:

template <typename T>
void f(T value);

enum cars { ford, volvo, saab, subaru, toyota };
enum colors { red, black, green, blue };

template <>
void f<cars>(cars) { }

template <>
void f<colors>(colors) { }

int main() {
    f(ford);
    f(red);
}
Run Code Online (Sandbox Code Playgroud)

  • 那不行,因为我事先没有枚举类型. (3认同)