【发布时间】:2014-04-12 22:42:06
【问题描述】:
我最近了解到模板模板参数的存在,现在想知道这样的事情是否可能:
template<template<class... > class Container, typename... args>
struct ContainerTemplate
{
using container = std::tuple<Container<args...>...>;
};
我想要的是一个模板,它获取一个 Container 或其他模板类作为模板模板参数,然后扩展其余模板参数,如果 Container 有 N 个模板参数,我给 N * M 个模板args 的参数我用 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>>
同时
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>>
有没有办法做到这一点? 问题是您是否可以找出 Container 需要多少模板参数。
编辑: 如果您需要在大小为 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
【问题讨论】:
-
第一个?容易地。第二个?笏。它应该如何知道它应该传递给该类型的参数数量? (请注意,标准容器的模板参数比您想象的要多。
-
我知道他们有更多只是为了简化。我的问题是是否有可能以任何方式确定模板参数的数量,然后挽救该信息以获得我想要的
-
编译器无法读懂你的想法,抱歉。
-
@Griwes 这就是为什么他想知道如何告诉他...
-
我可以看到有一种方法可以制作一个简单的贪婪版本并使用 SFINAE 忽略那些不起作用的版本,但我不知道从哪里开始。
标签: c++ templates c++11 variadic