class 的类型模板参数限制范围

Limit range of type template arguments for class

如果没有任意类型定义,我怎么能有这种效果?

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

是否有更优雅的方法来生成此内容,以便 Entity 只能使用 PrimarySecondary 作为模板参数实例化?

修复代码中的错误后:

在 C++1z 中,您可以轻松地使用 std::disjunction:

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

在 C++11 中,您可以将 disjuncation 实现为

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

然后将您的 class 模板定义为

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

您可以更进一步,创建 enable_if_any 可以解析为 void 的别名:

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