> I could not get any way to implement the isNbrOdd function outside the class body
> Is there a way to do so thanks in advance
You can define it outside the class body, just as you would for any other member function.
Because it is a template member,
a. define it as a template
b. define it in the header
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
class myClass
{
public :
template<class T> bool isNbrOdd(T nbr) ;
};
template<class T>
bool myClass::isNbrOdd(T nbr)
{
if(typeid(T)==typeid(size_t))
{
if(nbr%2)
return true;
return false;
}
else{
cout << "You should use the size_t/unsigned int type" << endl;
return false;
}
}
|
However,
typeid(T)==typeid(size_t)
is not a particularly good idea; it is (logically) evaluated at runtime.
And therefore, if we try to call
myClass::isNbrOdd()
with (say) a
double
, we would get a compile-time error:
nbr%2
is an invalid operation on a double.
A better approach would be to use SFINAE:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
#include <iostream>
#include <type_traits>
class myClass
{
public :
template < typename T > inline static
typename std::enable_if< std::is_unsigned<T>::value, bool >::type
isNbrOdd( T nbr ) ;
template < typename T > inline static
typename std::enable_if< !std::is_unsigned<T>::value, bool >::type
isNbrOdd( T nbr ) ;
};
template < typename T >
typename std::enable_if< std::is_unsigned<T>::value, bool >::type
myClass::isNbrOdd( T nbr ) { return nbr%2 ; }
template < typename T >
typename std::enable_if< !std::is_unsigned<T>::value, bool >::type
myClass::isNbrOdd( T )
{
std::cout << "please use an unsigned integral type\n" ;
return false ;
}
int main()
{
std::cout << std::boolalpha ;
std::cout << "unsigned long long: " << myClass::isNbrOdd( 79ULL ) << "\n\n" ;
std::cout << "double: " << myClass::isNbrOdd( 79.0 ) << "\n\n" ;
unsigned short s = 79 ;
std::cout << "unsigned short: " << myClass::isNbrOdd(s) << '\n' ;
}
|
http://coliru.stacked-crooked.com/a/19230bf96e0878b1