Runtime typeswitch for type lists as a switch instead of nested if?

This is from TTL:

////////////////////////////////////////////////////////////
//  run-time type switch
template <typename L, int N = 0, bool Stop=(N==length<L>::value) > struct type_switch;

template <typename L, int N, bool Stop>
  struct type_switch
  {
    template< typename F >
      void operator()( size_t i, F& f )
      {
        if( i == N )
        {
          f.operator()<typename impl::get<L,N>::type>();
        }
        else
        {
          type_switch<L, N+1> next;
          next(i, f);
        }
      }
  };

It is used to type types in a TypeList. The question is that they do this through a series of nested ifs. Is there a way to make this switch type as a single select statement instead?

Thank!

+2
source share
3 answers

You will need a preprocessor to create a large one switch. You will need get<>to search for no-op outside the list. Check the compiler output to make sure that unused cases do not produce a result if you like it; adjust if necessary, v).

Take a look at the Preprocessor Boost library if you are interested in this ...

template <typename L>
  struct type_switch
  {
    template< typename F >
      void operator()( size_t i, F& f )
      {
        switch ( i ) {
         #define CASE_N( N ) \
         case (N): return f.operator()<typename impl::get<L,N>::type>();
         CASE_N(0)
         CASE_N(1)
         CASE_N(2)
         CASE_N(3) // ad nauseam.
      }
  };
+2

.

. , , .

0

You can always use binary search instead of linear search. It would be more difficult and more likely to have errors (the binary search was surprisingly easily confused).

You can also manually expand N type_switch::operator(), where N is some reasonable upper bound for the number of list lengths you will have in your program.

0
source

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


All Articles