C++: type Length from float
This is kinda like my earlier question: C++: Vector3 type "wall"?
Except, now, I want to do this to a builtin rather then a user created type.
So I want a type "Length" that behaves just like float -- except I'm going to make it's construc开发者_开发技巧tor explicit, so I have to explicitly construct Length objects (rather than have random conversions flying around).
Basically, I'm going into the type-a-lot camp.
Like suggested in a comment over at your other question you can use units from boost. This should be explicit and still manageable.
It sounds like you want to wrap a float primitive in your own class. Here's an example to get you started:
class Length
{
protected:
float value_;
public:
Length(float value) : value_(value) { }
static Length operator +(Length a, Length b) { return Length(a.value_ + b.value_); }
static Length operator -(Length a, Length b) { return Length(a.value_ - b.value_); }
static Length operator *(Length a, Length b) { return Length(a.value_ * b.value_); }
static Length operator /(Length a, Length b) { return Length(a.value_ / b.value_); }
};
But, using the boost Units library is a much better choice in the long run...
精彩评论