Limit range of type template arguments for class

狂风中的少年 提交于 2020-01-24 20:14:31

问题


How can I have this effect without the arbitrary typedefs?

#include <type_traits>
#include <iostream>

typedef int Primary;
typedef float Secondary;

template<Class C, std::enable_if<std::is_same<Class, Primary>::value || std::is_same<Class, Secondary>::value> = 0>
class Entity {
public:
    template<std::enable_if<std::is_same<Class, Secondary>::value>::type = 0>
    void onlyLegalForSecondaryEntities() {
        std::cout << "Works" << std::endl;  
    }
};

int main() {
    Entity<Secondary> e;
    e.onlyLegalForSecondaryEntities();
    return 0;
}

Is there a more elegant way to produce this so that Entity can only be instantiated with Primary or Secondary as template arguments?


回答1:


After fixing the errors in your code:

In C++1z you can easily roll a trait is_any with std::disjunction:

template<typename T, typename... Others>
struct is_any : std::disjunction<std::is_same<T, Others>...>
{
};

In C++11, you can implement disjuncation as

template<class...> struct disjunction : std::false_type { };
template<class B1> struct disjunction<B1> : B1 { };
template<class B1, class... Bn>
struct disjunction<B1, Bn...> 
    : std::conditional<B1::value != false, B1, disjunction<Bn...>>::type { };

Then define your class template as

template<class C, typename std::enable_if<is_any<C, Primary, Secondary>::value>::type* = nullptr>
class Entity {
public:
    template<typename std::enable_if<std::is_same<C, Secondary>::value>::type* = nullptr>
    void onlyLegalForSecondaryEntities() {
        std::cout << "Works" << std::endl;
    }
};

demo

You can take this further and make enable_if_any alias that would resolve to void if possible:

template<typename This, typename... Elems>
using enable_if_is_any = typename std::enable_if<is_any<This, Elems...>::value>::type;

template<class C, enable_if_is_any<C, Primary, Secondary>* = nullptr>
class Entity {
public:
    template<typename std::enable_if<std::is_same<C, Secondary>::value>::type* = nullptr>
    void onlyLegalForSecondaryEntities() {
        std::cout << "Works" << std::endl;
    }
};

demo



来源:https://stackoverflow.com/questions/40496602/limit-range-of-type-template-arguments-for-class

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