Type C ++ recursive type inference

I am interested in learning a little about meta-programming patterns. In the code below, I am trying to find an unsigned integral type large enough to store the N bits specified at compile time using some template recursion.

template <typename T> struct NextIntegralType { }; template <> struct NextIntegralType<void> { typedef unsigned char type; }; template <> struct NextIntegralType<unsigned char> { typedef unsigned short type; }; ...More type 'iteration' here... template<size_t BITS, typename T> struct FindIntegralType2 { typedef std::conditional<BITS <= sizeof(typename T::type)*8, T, FindIntegralType2<BITS, NextIntegralType<typename T::type>>> _type; typedef typename _type::type type; }; template<size_t BITS> struct FindIntegralType { typedef typename FindIntegralType2<BITS, NextIntegralType<void>>::type type; }; 

When I declare a variable and assign it an integer value ...

 FindIntegralType<15>::type test(4000); 

I get the following:

 error: no matching function for call to 'FindIntegralType2<15u, NextIntegralType<unsigned char> >::FindIntegralType2(int)' note: candidates are: note: constexpr FindIntegralType2<15u, NextIntegralType<unsigned char> >::FindIntegralType2() note: candidate expects 0 arguments, 1 provided note: constexpr FindIntegralType2<15u, NextIntegralType<unsigned char> >::FindIntegralType2(const FindIntegralType2<15u, NextIntegralType<unsigned char> >&) note: no known conversion for argument 1 from 'int' to 'const FindIntegralType2<15u, NextIntegralType<unsigned char> >&' 

My recursion doesn't seem to "unwind." Can someone point me in the right direction?

Note. I am using GCC 4.6 .

EDIT:
I found a message that I missed earlier:
Automatically select a variable type large enough to store the specified number

Which indicates the answer in boost (where they always are):
boost_integer

This should solve both my practical need and intellectual curiosity.

+6
source share
1 answer

Your problem is that _type::type evaluates to std::conditional<...>::type , not FindIntegralType2<...>::type . Change it to typedef typename _type::type::type type; (too many type x_X). This should solve your problem.

+2
source

Source: https://habr.com/ru/post/916504/


All Articles