Re: Is this the correct way to use type specializations
On 2008-09-07 09:54, fabian.lim@gmail.com wrote:
Hi,
I am a newbie to C++, however, I programmed quite alot in C before.
This is my first attempt at OOP. In the following segment of my code,
Im trying to implement (as an exercise) a binary variable class. I
know this is extremely redundant :) but im learning so please bear
with me :) . Anyways, Notice that I have have two "=" operator
overloads. The 1st case takes care of x=y, where both x and y are
binary variables. The 2nd case takes care of x=1 or x=0. As you can
see, both chunks of code are extremely redundant. So my question is,
is there any better way to do this?
//********************** START: BINARY VARIABLES
*************************
class Binary {
char bit;
public:
//********************************************************
// Constructors and Destructor
Binary() { bit =0; };
~Binary(){ };
//********************************************************
// Copiers
//copy constructors
Binary( const Binary& val) { bit = val.bit; };
Binary( const int& val) { bit = val; }; //int specialization
//assignments
Binary& operator=(const Binary& rhs) {
bit = rhs.bit;
return *this;
}
Binary& operator=(const int& rhs) { //int specialization
bit = rhs;
return *this;
}
};
Looks fine to me. If you look closely you see that there is not much
redundancy at all, the only thing both the assignment operators have in
common is the "return *this;" statement, and you'll find them in all
assignment operators. If you do end up with a lot in duplication it
might be worth to break it out into a private function with does the
common parts and then call that function from those places that needs it.
Just a question tough, if the class handles binary values you really
should check the int value in the constructor and assignment operator so
you do not end up storing a value like 34 instead of just 1 or 0. You
might also want to us an initialisation list instead of assignments in
the constructor (and drop the ; after the constructor bodies):
Binary( const Binary& val)
: bit(val.bit)
{ }
Binary( const int& val)
: bit(val > 0 ? 1 : 0)
{ }
Binary& operator=(const int& rhs)
{
bit = rhs > 0 ? 1 : 0;
return *this;
}
If you use something like this you will also reduce the amount of
redundancy between the assignment operators.
--
Erik Wikstr??m