Originally Posted by
pheres
would do the job. The operators could probably derived from a base class which forwards them to the operators for the build in types.
I suppose that if you wanted to be funny/paranoid, you could do something like this:
Code:
template<typename T, typename Tag>
class Number;
template<typename T, typename Tag>
bool operator==(const Number<T, Tag>& lhs, const Number<T, Tag>& rhs);
template<typename T, typename Tag>
class Number
{
public:
Number(T n = T()) : n(n) {}
Number& operator+=(const Number& other)
{
n += other.n;
return *this;
}
friend bool operator== <>(const Number<T, Tag>& lhs, const Number<T, Tag>& rhs);
// various other operators
// ...
private:
T n;
};
// ...
template<typename T, typename Tag>
inline bool operator==(const Number<T, Tag>& lhs, const Number<T, Tag>& rhs)
{
return lhs.n == rhs.n;
}
struct AreaTypeTag {};
typedef Number<double, AreaTypeTag> AreaType;
struct PriceTypeTag {};
typedef Number<double, PriceTypeTag> PriceType;
int main()
{
AreaType area;
PriceType price;
if (area == area)
{
// okay
}
if (area == price)
{
// compile time error
}
area += area; // okay
area += price; // compile time error
}
Originally Posted by
pheres
But the Question is: Would the resulting compiled code be slower than code which uses plain double?
A quick assembly output comparison with my version shows that it could well be a no - the assembly output was exactly the same (once I removed the error causing code) as if I had directly typedef'ed int to AreaType and PriceType.