9

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

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...>;
};
4

2 回答 2

6

我不认为你能做到这一点。引用 N4606:

§14.3.3 [temp.arg.template]/1

模板模板参数的模板参数应该是类模板或别名模板的名称,表示为 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

现场演示

于 2016-10-23T09:20:33.717 回答
0

PutTupleInTV 与 PutTupleInV 的名称不同。您没有专门化模板 PutTupleInV,而是使用专门化语法来创建新的东西,称为 PutTupleInTV。

于 2016-10-23T08:47:25.493 回答