c++ - 变量模板模板?

标签 c++ c++14 c++17 template-templates variable-templates

假设你有一个元组类型,你想提取它的模板参数包以实例化另一个模板。如果那是一个类型模板,那么我可以有一个像这样的实用程序:

template < typename Tuple, template <typename...> typename What >
struct PutTupleInT;

template < typename... Types, template <typename...> typename What >
struct PutTupleInT<std::tuple<Types...>, What>
{
    using Result = What<Types...>;
};

但是如果想要的模板是可变模板呢?同时 template <typename...> typename What是类型模板的“占位符”,那么变量模板的“占位符”是什么?

我已经为 clang-4.0.0(目前唯一支持自动类型的非类型模板参数的编译器)尝试了以下方法,但它失败了。实际上我不确定这是否是 C++17 的正确语法。

template < typename Tuple, template <typename...> auto What >
struct PutTupleInV;

template < typename... Types, template <typename...> auto What >
struct PutTupleInV<std::tuple<Types...>, What>
{
    static constexpr auto value = What<Types...>;
};

最佳答案

我认为你做不到。引用 N4606:

§14.3.3 [temp.arg.template]/1

A template-argument for a template template-parameter shall be the name of a class template or an alias template, expressed as id-expression.

可变模板不符合此要求。


你可以稍微作弊并使用代理类型来选择模板:

template < typename Tuple, class Proxy>
struct PutTupleInTV;

template < typename... Types, class Proxy>
struct PutTupleInTV<std::tuple<Types...>, Proxy>
{
    static constexpr auto value = Proxy::template value<Types...>;
};

然后是

template<typename...> struct foo{};
template<typename... Ts> constexpr foo<Ts...> foo_v{};
struct use_foo
{
    template<typename... Ts>
    static constexpr auto value = foo_v<Ts...>;
};

你可以说

PutTupleInTV<tup, use_foo>::value

live demo

关于c++ - 变量模板模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40201020/

相关文章:

c++ - 如何在 C++ 的类主体中使用定义在类 def 中的字符数组数组?

c++ - 如何访问 integer_sequence 的第 n 个值?

c++ - 不同编译器引用未知边界数组的奇怪行为

C++17 static 和 constexpr

c++ - 为什么 std::optional<int> 的构造比 std::pair<int, bool> 更昂贵?

C++ 仅当模板为字符串类型时才执行小写转换

c++ - 堆分配内存的线程安全

c++ - 是否可以转发声明一个静态数组

c++ - 如果将 Memoization 添加到 Recursion,则错误的解决方案

c++ - 正确转换为指向返回函数的函数的函数指针