Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++11 限制类的类型模板参数的范围_C++11_Templates_Sfinae - Fatal编程技术网

C++11 限制类的类型模板参数的范围

C++11 限制类的类型模板参数的范围,c++11,templates,sfinae,C++11,Templates,Sfinae,如果没有任意的typedef,我怎么能有这种效果呢 #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>:

如果没有任意的typedef,我怎么能有这种效果呢

#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;
}
#包括
#包括
typedef int Primary;
类型DEF浮动次级;
模板
类实体{
公众:
模板
仅适用于第二实体()的void{

std::cout修复代码中的错误后:

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

template<typename T, typename... Others>
struct is_any : std::disjunction<std::is_same<T, Others>...>
{
};
然后将类模板定义为

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

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