Why doesn't this recursive pattern work?

So, I tried to create what I think would be a simple recursive pattern to create a large but trivial nested type:

#include <type_traits>
#include <typeinfo>

#include <boost/core/demangle.hpp>

template <typename T>
struct A {};

template <typename T, int N>
struct Nest
{
  using type = Nest<A<T>, N-1>
};

template <typename T>
struct Nest<T, 0>
{
  using type = T;
};

int main()
{
  typename Nest<A<int>, 20>::type x;
  std::cout << boost::core::demangle(typeid(x).name());
};

      

Output of this program

Nest<A<A<int> >, 19>

      

I was expecting to see a list A<int>

nested in 19 layers A<>

. What is going on here and what do I need to do to get the effect I'm looking for?

+3


source to share


2 answers


Forgot the recursion step:

template <typename T, int N>
struct Nest
{
  using type = Nest<A<T>, N-1>::type
};

      



May be needed typename

- I don't have access to the compiler right now.

+3


source


This is the cleanest way to do recursion like this:

template <typename T>
struct A {};

template <typename T, unsigned N>
struct Nest:Nest<A<T>,N-1> {};

      

You can read above how "A Nest<T,N>

is Nest<A<T>,N-1>

" if you are fluent in C ++.

Then let's add an exception:



template <typename T>
struct Nest<T, 0> {
  using type = T;
};

      

Next, we a using

to get rid of spam typename

elsewhere:

template <typename T, unsigned N>
using Nest_t = typename Nest<T,N>::type;

int main() {
  Nest_t<int, 20> x;
  std::cout << boost::core::demangle(typeid(x).name());
};

      

+2


source







All Articles