我不能想出一個方法來定義一個通用元函數,它這樣做,但這裏是一個可能的解決方法:
#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;
};
但鏘3.2抱怨說,U的類型不能被推斷,所以這種專業化的get_type
將永遠不會被使用。所以如果你遵循這種方法,你將不得不明確定義每個專業。根據您的使用情況,這可能也可能不會被接受。希望能幫助到你。
你的意思是什麼variadic列表?如果你通過'MyClassN'還沒有列表。列表只有一個模式,其實例可能是空的或不是。你的意思是「和size_t如果沒有參數包」? –
' :: type'可能會調用另一個類似於'template class T>'的結構體。但是如何推斷'Kind ...'? –
Vincent