使用非标量类型实例化模板时修复编译错误

时间:2017-04-24 00:06:13

标签: c++ c++11 templates

   #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";
   }

这会返回所需的结果......

int: 2147483647
short: 32767
float: 0

但是,如果我取消注释最后一行,我会得到:

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 type ‘int’
       if ( std::is_integral<T>::value ) return (int) std::numeric_limits<T>::max();

我希望函数在这种情况下返回0

1 个答案:

答案 0 :(得分:4)

我建议你将功能分成两个不同的功能,启用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; }