使用variadic模板

Using with variadic template

本文关键字:模板 variadic 使用      更新时间:2023-10-16

我知道以下代码编译:

template<class Type>
class Foo
{
    using type = Type;
};

现在,我正在尝试编译以下代码:

template<class Type, class... OtherTypes>
class Foo
{
    using type = Type;
    // using types = OtherTypes;
    // using... types = OtherTypes;
    // using types... = OtherTypes;
    // using types = OtherTypes...;
    // using types... = OtherTypes...;
};

我在注释中尝试了代码的所有选项,但没有任何编译。我该如何修复?

您不能将类型类型作为类中的类型。

最接近的是:

template<class...Ts> struct types_t { constexpr types_t(){}; };
template<class...Ts> constexpr types_t<Ts...> types{};

这些是代表类型包的值和类型。

template<class Type, class... OtherTypes>
class Foo
{
  using type=Type;
  using types=types_t<OtherTypes...>;
};

然后,我们可以编写消耗捆绑类型并在其他地方使用它们的辅助功能。

template<template<class...>class Z, class Types>
struct apply_types;    
template<template<class...>class Z, class...Ts>
struct apply_types<Z, types_t<Ts...>> {
  using type=Z<Ts...>;
};
template<template<class...>class Z, class Types>
using apply_types_t = typename apply_types<Z,Types>::type;

现在apply_types< some_template, some_types_t >将捆绑包中的类型带到模板中。

让我们假设要将包作为模板参数使用。然后,您可以尝试以下方法。

#include <utility>
template <class... Types>
struct Foo {};
template <template <class...> class Template,
          class... Types,
          template <class...> class T>
Template<Types...> foo(const T<Types...> &);
template <template <class...> class Template, class T>
using Type = decltype(foo<Template>(std::declval<T>()));
int main() {
  using T = Foo<int, int>;
  // As template argument
  using Tuple = Type<std::tuple, T>;
  static_assert(std::is_same<Tuple, std::tuple<int, int> >::value, "");
  return 0;
}