我想不出一种方法来定义一个通用元函数来实现它,但这里有一个可能的解决方法:
#include <iostream>
#include <type_traits>
using namespace std;
// PRIMARY TEMPLATE
template<typename T>
class something
{
};
// SPECIALIZATIONS FOR int
template<typename T, int... U, template<typename, int...> class L>
class something<L<T, U...>>
{
public:
typedef int type;
};
template<typename T, template<typename, int...> class L>
class something<L<T>>
{
public:
typedef size_t type;
};
// SPECIALIZATIONS FOR unsigned int
template<typename T, unsigned int... U, template<typename, unsigned int...> class L>
class something<L<T, U...>>
{
public:
typedef unsigned int type;
};
template<typename T, template<typename, unsigned int...> class L>
class something<L<T>>
{
public:
typedef size_t type;
};
/* ... OTHER SPECIALIZATIONS ... */
struct A {};
struct B {};
int main()
{
static_assert(is_same<something<MyClass1<A, 1, 2>>::type, int>::value, "Error!");
static_assert(is_same<something<MyClass1<A>>::type, size_t>::value, "Error!");
static_assert(is_same<something<MyClass2<B, 1U, 2U, 3U>>::type, unsigned int>::value, "Error!");
static_assert(is_same<something<MyClass2<B>>::type, size_t>::value, "Error!");
return 0;
}
我试图只编写涵盖所有情况的单一专业化,如下所示:
template<typename U, typename T, U... V, template<typename, U...> class L>
class something<L<T, V...>>
{
public:
typedef U type;
};
但是 Clang 3.2 抱怨 U 的类型无法推断,所以get_type
永远不会使用这种特化的。因此,如果您遵循这种方法,您将必须明确定义每个专业。这可能会或可能不会接受,具体取决于您的用例。希望能帮助到你。