简体   繁体   中英

Using with variadic template

I know that the following code compile:

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

now, I'm trying to compile the following code:

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

I tried all of the options of the code in comments, but none of them compile. How can I fix it?

You cannot have a pack of types as a type in a class.

The closest you can get is roughly:

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

these are values and types that represent a package of types.

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

then we can write helper functions that consume bundled-up types and use them elsewhere.

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;

now apply_types< some_template, some_types_t > takes the types in the bundle and passes them to the template.

Let's assume that you want to use the pack as template argument. Then you can try the following approach.

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM