变量模板模板?

Vah*_*agn 9 c++ template-templates variable-templates c++14 c++17

假设您有一个元组类型,并且您想要提取其模板参数包以便实例化另一个模板.如果那是一个类型模板,那么我可以有这样的实用程序:

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...>;
};
Run Code Online (Sandbox Code Playgroud)

但是,如果所需模板是可变模板呢?虽然template <typename...> typename What是类型模板的"占位符",但是变量模板的"占位符"是什么?

我已经尝试了以下forng-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...>;
};
Run Code Online (Sandbox Code Playgroud)

krz*_*zaq 6

我认为你不能这样做.引用N4606:

§14.3.3[temp.arg.template]/1

模板template-parametertemplate-argument应该是类模板或别名模板的名称,表示为 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...>;
};
Run Code Online (Sandbox Code Playgroud)

然后为

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...>;
};
Run Code Online (Sandbox Code Playgroud)

你可以说

PutTupleInTV<tup, use_foo>::value
Run Code Online (Sandbox Code Playgroud)

现场演示