编译时间 class 通过枚举模板参数选择模板
Compile time class template selection by enum template parameter
我正在尝试 select 基于给定枚举模板参数 (store_type) 的 class 模板。现在我实例化一个使用它的 class,但它似乎总是尝试为此 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;
您忘记了专业化中的 3rd 模板参数。
template<class T> struct get_store_type<T, lockless, void >
^^^^
下面代码的输出是1,2和3:
#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;
}
我正在尝试 select 基于给定枚举模板参数 (store_type) 的 class 模板。现在我实例化一个使用它的 class,但它似乎总是尝试为此 class.
实例化 basic_storeenum 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;
您忘记了专业化中的 3rd 模板参数。
template<class T> struct get_store_type<T, lockless, void >
^^^^
下面代码的输出是1,2和3:
#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;
}