为枚举类型参数专门化成员模板 [英] Specializing member template for enum type arguments

查看:34
本文介绍了为枚举类型参数专门化成员模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,Foo<T>::setValue 非常适合我的目的,除非 T 是名为 TYPE 的类枚举 例如Bar::TYPEBaz: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.

因此,我很感激在不命名 BarBaz 的情况下专门化 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_ifis_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆