- Prison Code Breaker Diary -

=> aka: Nhật Kí Code Tù

Categories

Original Discussion: -> [Cviet]

Code Relax #2 [ by rox_rook  ]

Given a template to get sum below

template< typename T >
inline
T calculate_sum_of_element( const T* i, const T* e )
{
    T sum = T( ); // a zero value for any type
    while( i != e )
    {
        sum += *i;
        ++i;
    }

    return sum;
}

Try this on int and char array

#include <iostream>

using namespace std;

template< typename T >
inline
T calculate_sum_of_element( const T* i, const T* e )
{
    T sum = T( ); // a zero value for any type
    while( i != e )
    {
        sum += *i;
        ++i;
    }

    return sum;
}

int main( )
{
    int int_ary[ 3 ] = { 1, 2, 3 };
    cout << calculate_sum_of_element( int_ary, int_ary + 3 ) << endl;
    
    char char_ary[ 3 ] = { 'a', 'b', 'c' };
    cout << calculate_sum_of_element( char_ary, char_ary + 3 ) << endl;
    return 0;
}

The result for int is 6 as expected; however, for char it supposed to be 97 + 98 + 99 = 294, but the character '&' is printed out.

Requirement
+ Re-write the given template function to make char data type return an int value
+ Language in use: C++

Solution [ by author, rox_rook ]

#include <iostream>
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

template< typename T >
class Trait;

template< >
class Trait< char >
{
public :
    typedef int SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< >
class Trait< short >
{
public :
    typedef short SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< >
class Trait< unsigned >
{
public :
    typedef unsigned SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< >
class Trait< double >
{
public :
    typedef double SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< >
class Trait< int >
{
public :
    typedef int SumType;
    static SumType zero( )
    {
        return 0;
    }
};

template< typename T >
inline
typename Trait< T >::SumType calculate_sum_of_element( const T* i, const T* e )
{
    typedef typename Trait< T >::SumType SumType; // create shortcut, less typo
    SumType sum = Trait< T >::zero( );
    while( i != e )
    {
        sum += *i;
        ++i;
    }

    return sum;
}

int main( )
{
    char char_ary[ 3 ] = { 'a', 'b', 'c' };
    cout << calculate_sum_of_element( char_ary, char_ary + 3 ) << endl;
    double d_ary[ 3 ] = { 1.1, 2.2 , 3.3 };
    cout << calculate_sum_of_element( d_ary , d_ary + 3 ) << endl;    
    int i_ary[ 3 ] = { 1, 2 , 3 };
    cout << calculate_sum_of_element( i_ary , i_ary + 3 ) << endl;      
}


Evaluation
- It's freaking unthinking of....lol

0 comments

Post a Comment