Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - std::enable_if for more types

I have a function:

template <typename T,
  typename std::enable_if <std::is_same<T, int>::value == true>::type* = nullptr>
void test(T i)
{
   //process data
}

It works.

However, I need to enable this function not only for int, but for float and const char * as well... how to do this without writing the same method 3x times?

like image 873
Martin Perry Avatar asked Dec 09 '16 07:12

Martin Perry


2 Answers

Like this:

template <typename T,
  typename std::enable_if <std::is_same<T, int         >::value ||
                           std::is_same<T, float       >::value ||
                           std::is_same<T, const char *>::value>::type* = nullptr>
void test(T i)
{
   //process data
}
like image 178
Ralph Tandetzky Avatar answered Oct 18 '22 01:10

Ralph Tandetzky


A generic solution for C++17 ( checked on godbolt.org)

#include <type_traits>

template< typename U, typename ... Ts > struct belong_to
{
  // before C++17 value will have to be defined recursively on the head of Ts
  static constexpr bool value = (std::is_same< U, Ts >::value || ... );
  using type = typename std::enable_if< value, U > ::type;
};

// usage example:
template< typename T >
using testable = typename belong_to< T, int, float, const char >::type;

template< typename T > void test ( testable< T > i ) 
{
    // test process
}

int main()
{
   test< int        > ( 3 );
   test< float      > ( 3.0 );
   test< const char > ('c');
   // test< signed char >( 1 ); does not compile!!!
}
like image 3
user7272101 Avatar answered Oct 18 '22 01:10

user7272101