简体   繁体   English

通过枚举模板参数编译时间类模板选择

[英]Compile time class template selection by enum template parameter

I am trying to select a class template based on a given enum template parameter (store_type). 我试图根据给定的枚举模板参数(store_type)选择一个类模板。 Now I instantiate a class that uses this, but it seems to always try to instantiate the basic_store for this class. 现在我实例化一个使用它的类,但似乎总是试图为这个类实例化basic_store。

enum store_type
{
    none,
    basic,
    lockless,
};

template<class T, store_type S = none, typename = void>
struct get_store_type
{
};

template<class T>
struct get_store_type<T, basic,
typename std::enable_if<!std::is_abstract<T>::value>::type>
{
    using store_type = typename basic_store<T>;
};

template<class T>
struct get_store_type<T, lockless>
{
    using store_type = typename lockless_store<T>;
};

template<typename T, store_type S>
class client
{
public:
    using my_store_type = typename get_store_type<T, S>::store_type;
}

//Tries to instantiate a basic store... which is not allowed.
client<SomeAbstractType, lockless> something;

You forgot the 3rd template argument in the specialization. 您忘记了专业化中的第3个模板参数。

template<class T> struct get_store_type<T, lockless, void >
                                                     ^^^^

The output of the following code is 1 , 2 and 3 : 下面的代码的输出为1,23:

#include <iostream>

enum store_type { none, basic, lockless };

template<class T, store_type S = none, typename = void>
struct get_store_type
{ int a = 1; };

template<class T>
struct get_store_type<T, basic, typename std::enable_if<!std::is_abstract<T>::value>::type>
{ int b = 2; };

template<class T>
struct get_store_type<T, lockless, void > 
{ int c = 3; };

struct Any{};

int main( void )
{
    get_store_type<int> storeA;
    get_store_type<Any, basic> storeB;
    get_store_type<int, lockless> storeC;

    std::cout << storeA.a << std::endl;
    std::cout << storeB.b << std::endl;
    std::cout << storeC.c << std::endl;    

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM