Fix compilation error when instantiating with non-scalar type

   #include <limits>
   #include <iostream>
   using std::cerr;

   template< typename T >
   int get_max_if_integral()
      {
      if ( std::is_integral<T>::value ) return (int) std::numeric_limits<T>::max();
      else return 0;
      }

struct S {};

int main()
   {
   cerr<<"int: "<<get_max_if_integral<int>()<<"\n";
   cerr<<"short: "<<get_max_if_integral<short>()<<"\n";
   cerr<<"float: "<<get_max_if_integral<float>()<<"\n";
// cerr<<"S: "<<get_max_if_integral<S>()<<"\n";
   }

      

This returns the desired result ...

int: 2147483647
short: 32767
float: 0

      

However, if I uncomment the final line, I get:

x.cpp: In instantiation of ‘int get_max_if_integral() [with T = S]’:
x.cpp:22:40:   required from here
x.cpp:11:82: error: invalid cast from type ‘S’ to typeintif ( std::is_integral<T>::value ) return (int) std::numeric_limits<T>::max();

      

I would like the function to return 0

in this case.

+3


source to share


1 answer


I suggest you split your function into two different functions included by SFINAE



template <typename T>
typename std::enable_if<true == std::is_integral<T>::value, int>::type
     get_max_if_integral ()
 { return (int) std::numeric_limits<T>::max(); }

template <typename T>
typename std::enable_if<false == std::is_integral<T>::value, int>::type
     get_max_if_integral ()
 { return 0; }

      

+4


source







All Articles