Specializing member template for enum type arguments

纵饮孤独 提交于 2019-12-06 11:45:14

You can do this with something like:

#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;
};

Where enable_if picks which version to use based on the is_enum type trait.

The example used C++11 enable_if and is_enum but boost has similar for pre-C++11 also.

Consider this:

#include <iostream>

class Bar
{
public:
    enum TYPE{ ONE , TWO };
};

class Baz
{
public:
    enum TYPE{ SIX , TEN };
};

template<typename T>
class Foo
{
public:
    template<typename C> void setValue(const C &m_value, ...) 
    {
        std::cout << "normal" << std::endl;
    }

    template<typename C> void setValue(const C &m_value, typename C::TYPE fake = C::TYPE()) 
    {
        std::cout << "TYPE'ed" << std::endl;
    }

private:
    T m_value;
};


int main()
{
    Foo<int> f1;
    Foo<Bar> f2;
    Foo<Baz> f3; 

    f1.setValue(1);
    f2.setValue(Bar());
    f3.setValue(Baz());

    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!