>> If I am going to write chess programs, probably I would declare the same variable but with all type of int.
I agree. The texual representation isn't really useful from within the class, so you could probably just translate from integer id to string when necessary. Here's a possible starting point:
Code:
#include <ostream>
#include <string>
namespace chess {
struct piece
{
enum color_type
{
first_color,
black = first_color,
white,
color_count
};
enum rank_type
{
first_rank,
king = first_rank,
queen,
castle,
bishop,
knight,
pawn,
rank_count
};
piece( int rank, int color, int ordinal = 0 )
: rank( rank ), color( color ), ordinal( ordinal )
{ }
friend bool operator == ( piece const& lhs, piece const& rhs )
{
return
lhs.rank == rhs.rank
&&
lhs.color == rhs.color
&&
lhs.ordinal == rhs.ordinal;
}
friend std::ostream& operator << ( std::ostream& out, piece const& rhs )
{
return out
<< translate_color( rhs.color ) << "."
<< translate_rank( rhs.rank ) << "."
<< rhs.ordinal;
}
static std::string translate_color( int color )
{
if( color == white )
return "white";
if( color == black )
return "black";
/*
Or maybe throw an exception here
*/
return std::string( );
}
static std::string translate_rank( int rank )
{
if( rank == king )
return "king";
if( rank == queen )
return "queen";
if( rank == castle )
return "castle";
if( rank == bishop )
return "bishop";
if( rank == knight )
return "knight";
if( rank == pawn )
return "pawn";
/*
Or maybe throw an exception here
*/
return std::string( );
}
static int ordinals_of_rank( int rank )
{
if( rank == king )
return 1;
if( rank == queen )
return 1;
if( rank == castle )
return 2;
if( rank == bishop )
return 2;
if( rank == knight )
return 2;
if( rank == pawn )
return 8;
/*
Or maybe throw an exception here
*/
return 0;
}
int
color;
int
rank;
int
ordinal;
};
} // namespace chess
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main( void )
{
using namespace chess;
using namespace std;
vector< piece >
pieces;
for( int color = piece::first_color; color < piece::color_count; ++color )
for( int rank = piece::first_rank; rank < piece::rank_count; ++rank )
for( int ordinal = 0, ordinal_count = piece::ordinals_of_rank( rank ); ordinal < ordinal_count; ++ordinal )
pieces.push_back( piece( rank, color, ordinal ) );
copy( pieces.begin( ), pieces.end( ), ostream_iterator< piece >( cout, "\n" ) );
return 0;
}