jeudi 26 décembre 2019

Tag dispatching to remove operators

I want to be able to use compile time information to prevent two objects of the same class being combined. In particular if a represents meters, and b uses centimeters I want the compiler to not allow their combination.

I think something like this should be possible with tags, but am slightly at a loss for how. I'm using the example of doubles here, but really the base type is more complicated, and I want to avoid having to redefine every single operator as there are enormous number. I want the class to behave exactly like the original class when interacting with other members of its tagged-class, but refuse the same operations if the tags don't match.

Something like this?

struct Meters{};
struct Centimeters{};

template < struct Units >
class DimensionedDouble : public double {
 // magic
}

int main(){
 DimensionedDouble<Meters> a(0.0), b(1.0);
 DimensionedDouble<Centimeters> c(2.0);

 std::cout << a+b << std::endl; // fine
 std::cout << a+c << std::endl; // compile error!

 return 1;
}

Aucun commentaire:

Enregistrer un commentaire