C++ 枚举的模板特化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1619993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Template specialization for enum
提问by nilton
Is it possible to specialize a templatized method for enums?
是否可以专门为枚举使用模板化方法?
Something like (the invalid code below):
类似于(下面的无效代码):
template <typename T>
void f(T value);
template <>
void f<enum T>(T value);
In the case it's not possible, then supposing I have specializations for a number of types, like int
, unsigned int
, long long
, unsigned long long
, etc, then which of the specializations an enum value will use?
在这种情况下这是不可能的,那么假如我有专业化的多种类型,如int
,unsigned int
,long long
,unsigned long long
,等等,那么其专业化的枚举值将使用?
回答by James McNellis
You can use std::enable_if
with std::is_enum
from <type_traits>
to accomplish this.
您可以使用std::enable_if
with std::is_enum
from<type_traits>
来完成此操作。
In an answer to one of my questions, litb posted a verydetailed and well-written explanation of how this can be done with the Boost equivalents.
在回答我的一个问题时,litb 发布了一份非常详细且写得很好的解释,说明如何使用 Boost 等效项来完成此操作。
回答by Thomas Padron-McCarthy
I'm not sure if I understand your question correctly, but you can instantiate the template on specific enums:
我不确定我是否正确理解您的问题,但您可以在特定枚举上实例化模板:
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);
}
回答by Ohad Schneider
Presumably, the only interesting thing you could do with a type that they only thing you know about it is that it's an enum, is cast it to its underlying type and operate on that. Here's how that might look like, using James' suggested approach (AKA SFINAE):
据推测,你可以对一个他们唯一知道的类型做的唯一有趣的事情是它是一个枚举,将它转换为它的底层类型并对其进行操作。下面是使用 James 建议的方法(AKA SFINAE)的样子:
void Bar(int b); // and/or other underlying types
template<typename T>
typename std::enable_if<std::is_enum<T>::value, void>::type
Foo(T enm)
{
Bar(static_cast<typename std::underlying_type<T>::type>(enm));
}
As a related bonus, here's a similar method that would only get resolved for a specific type of your choosing (replace bool in is_same
to the type of your choosing):
作为相关的奖励,这里有一个类似的方法,它只会针对您选择的特定类型得到解决(将 bool 替换is_same
为您选择的类型):
template<typename T>
typename std::enable_if<std::is_same<T,bool>::value, void>::type
Baz(T bl)
{
if (bl)
{
//...
}
else
{
//...
}
}