我最近了解到模板模板参数的存在,现在想知道是否可以这样做:
template<template<class... > class Container, typename... args>
struct ContainerTemplate
{
using container = std::tuple<Container<args...>...>;
};
我想要的是一个模板,它获取 Container 或其他一些模板类作为模板模板参数,然后以这样的方式扩展其余模板参数:如果 Container 有 N 个模板参数,并且我为 args 提供 N * M 模板参数我得到带有 N 个模板参数的 M 个模板实例化,例如:
ContainerTemplate<std::vector, int, short, char>
//assuming std::vector takes only 1 arg for simplicity
应该导致
container = std::tuple<std::vector<int>, std::vector<short>, std::vector<char>>
while
ContainerTemplate<std::map, int, int, short, short>
//assuming std::map takes only 2 args for simplicity
应该导致
container = std::tuple<std::map<int, int>, std::map<short, short>>
有什么办法可以做到这一点吗?
问题是您是否可以找出容器需要多少个模板参数。
编辑:
如果要求您以大小为 N 的元组传递附加参数,那就没问题了
ContainerTemplate<std::map, std::tuple<int, int>, std::tuple<short, short>>
编辑2:
所以我实际上找到了一种方法来确定模板模板参数的数量
template<typename... T>
struct TypeList
{
static const size_t Size = sizeof...(T);
template<typename T2>
struct PushFront
{
typedef TypeList<T2, T...> type_list;
};
};
template<template<class...> class Template, typename... Args>
struct SizeofTemplateTemplate
{
static const size_t Size = 0;
typedef TypeList<> type;
};
template<template<class...> class Template, typename Arg, typename... Args>
struct SizeofTemplateTemplate<Template, Arg, Args...>
{
template<typename... Args>
struct Test;
typedef char yes[1];
typedef char no[2];
template<typename... Args>
struct Test<TypeList<Args...>>
{
template<template<class...> class Template>
static yes& TestTemplate(Template<Args...>* arg);
template<template<class...> class Template>
static no& TestTemplate(...);
};
typedef typename SizeofTemplateTemplate<Template, Args...>::type::PushFront<Arg>::type_list type;
static const size_t Size = sizeof(Test<type>::TestTemplate<Template>(0)) == sizeof(yes) ? type::Size : SizeofTemplateTemplate<Template, Args...>::Size;
};
这样,下面的代码将打印 2
std::cout << SizeofTemplateTemplate<std::vector, int, std::allocator<int>, int, int>::Size << std::endl;
我现在唯一的问题是 dyp 的解决方案使 Visual Studio 编译器崩溃 xD
编辑3:
原始问题的完整解决方案在这里:https://stackoverflow.com/a/22302867/1366591 https://stackoverflow.com/a/22302867/1366591