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 39 40 41 42 43 44 45 46 47
|
#include <iostream>
#include <string>
#include <cstring>
// overload one for generic simple types
template < typename T > bool less( const T& a, const T& b ) { return a < b ; }
// overload two specifically (non-template) for c-style strings
bool less( const char* a, const char* b ) { return std::strcmp(a,b) < 0 ; }
// overload three for generic arrays of the same kind
template < typename T, std::size_t N > bool less( const T(&a)[N], const T(&b)[N] )
{
for( std::size_t i = 0 ; i < N ; ++i )
{
if( less( a[i], b[i] ) ) return true ;
else if( less( b[i], a[i] ) ) return false ;
}
return false ;
}
int main()
{
int i = 7, j = 8 ;
std::cout << std::boolalpha << less(i,j) << '\n' ; // overload one
char cstr1[10] = "abcd" ;
char cstr2[10] = "abcde" ;
std::cout << less( cstr1, cstr2 ) << '\n' ; // overload two
int arr1[8] = { 0, 1, 2, 3, 4, 5 } ;
int arr2[8] = { 0, 1, 2, 7, 4, 5 } ;
std::cout << less( arr1, arr2 ) << '\n' ; // overload three
// (which calls overload one for each element)
char arr2d_x[][5] = { "abcd", "efgh", "ijkl", "mnop" } ;
char arr2d_y[][5] = { "abcd", "Efgh", "IJKL", "mnop" } ;
std::cout << less( arr2d_x, arr2d_y ) << '\n' ; // overload three
// (which calls overload two for each element)
int arr2d_i[7][5] = { { 0, 1, 2, 3 }, { 4, 5, 6, 1 }, { 7, 8, 9 } } ;
int arr2d_j[7][5] = { { 0, 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 9 } } ;
std::cout << less( arr2d_i, arr2d_j ) << '\n' ; // overload three
// (which calls overload three for each sub-array)
// (which calls overload one for each element)
}
| |