does adding a dummy parameter to constructors of a class to solve calling ambiguity, violate any rule?
take following class and two object definitions:
class Rect{
public:
enum centimeter;
enum meter;
Rect(double len,double wid,enum centimeter){
length=(len/100);
width=(wid/100);
}
Rect(int len,int wid,enum meter){
length=len;
width=wid;
}
//rest of implementation
private:
double length;//in meters
double width;//in meters
};
Rect obj1(10,5,Rect::centimeter());开发者_开发百科
Rect obj2(10,5,Rect::meter());
two previous constructors have dummy enum parameters to solve calling ambiguity caused in case these dummy parameters didn't exist. Now in spite of possibility of using named constructors here, if I insist on using these dummy parameters, does this violate any coding rule that I should be aware of ?
I think it violates my taste. I would code it like this:
enum Unit {
Centimeter = 100,
Meter = 1
};
Rect(int len, int wid, Unit unit) {
length = len / (int) unit;
width = wid / (int) unit;
}
Rect obj1(10, 5, Rect::Centimeter);
Rect obj2(10, 5, Rect::Meter);
BOOST_STRONG_TYPEDEF could be the answer here.
BOOST_STRONG_TYPEDEF( double, Meter )
BOOST_STRONG_TYPEDEF( double, Centimeters)
BOOST_STRONG_TYPEDEF( double, Furlongs)
class Rect
{
public:
Rect(Meter len, Meter wid) : length(len), width(wid)
{};
Rect(Centimeter len, Centimeter wid) : length(len/100), width(wid/100)
{};
}
Rect obj1(Meter(10),Meter(5));
Rect obj1(Centimeter(10),Centimeter(5));
STL uses that idiom to differentiate iterator types in lieu of concepts.
Can't say this breaks a rule, but... It isn't easy to read.
Why can't you declare a
enum metrics {
centimeter,
meter
};
and use it as the constructor parameter? Or it can be
class Rect {
public:
static Rect CreateWithMeters(int width, int height);
static Rect CreateWithCentimenets(int width, int height);
}
Either is better than current code at my taste.
Rect(int len,int wid,enum centimeter){
length=(len/100);
width=(wid/100);
}
In addition to what others wrote, this logic is bad, because Rect(99,99,Rect::centimeter())
is equal to Rect(0,0,Rect::centimeter())
.
If you are storing meters internally, do not provide an interface with centimetres, not this way nor any other way.
精彩评论