问题描述
限时送ChatGPT账号..在下面的代码中,Foo<T>::setValue
非常适合我的目的,除非 T
是名为 TYPE 的类枚举
例如Bar::TYPE
和 Baz:TYPE
.
In the code below, Foo<T>::setValue
works well for my purposes, except in cases where where T
is a class enum named TYPE
e.g. Bar::TYPE
and Baz:TYPE
.
因此,我很感激在不命名 Bar
和 Baz
的情况下专门化 Foo<T>::setValue
的帮助,因为可能有几十个此类课程.
Therefore, I'd appreciate help specializing Foo<T>::setValue
without naming Bar
and Baz
, because there could be dozens of such classes.
class Bar
{
public:
enum TYPE{ ONE , TWO };
};
class Baz
{
public:
enum TYPE{ SIX , TEN };
};
template<typename T>
class Foo
{
public:
void setValue(){} // Need a different setValue if T is a class enum
private:
T m_value;
};
int main()
{
Foo<int> f1;
Foo<Bar::TYPE> f2;
Foo<Baz::TYPE> f3;
return EXIT_SUCCESS;
}
推荐答案
你可以这样做:
#include <type_traits>
template<typename T>
class Foo
{
public:
void setValue() {
setValueImpl<T>();
}
private:
template <class X>
typename std::enable_if<std::is_enum<X>::value, void>::type
setValueImpl() { std::cout << "Is enum" << std::endl; }
template <class X>
typename std::enable_if<!std::is_enum<X>::value, void>::type
setValueImpl() { std::cout << "Not enum" << std::endl; }
T m_value;
};
其中 enable_if
根据 is_enum
类型特征选择要使用的版本.
Where enable_if
picks which version to use based on the is_enum
type trait.
示例使用了 C++11 enable_if
和 is_enum
,但 boost 也适用于 pre-C++11.
The example used C++11 enable_if
and is_enum
but boost has similar for pre-C++11 also.
这篇关于为枚举类型参数专门化成员模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论