How to create a class whose interface matches the double, but on which templates can be specialized?

How to create a class whose interface matches the double, but whose template types are not dynamically reset to double?

The reason is because I have a runtime type system, and I want to have a type that works just like double:

template<int min_value, int max_value> class BoundedDouble: public double {}; 

And then use the specialized specialization to get runtime information for this type:

 template<typename T> class Type { etc. } template<int min_value, int max_value> class Type<BoundedDouble<min_value, max_value>> { int min() const { return min_value; } etc. } 

But you cannot inherit from double ...

0
source share
1 answer

You cannot receive from native types. Use composition instead:

 #include <cstdlib> #include <string> #include <stdexcept> #include <iostream> using namespace std; template<typename Type = double, const Type& Min = -10.0, const Type& Max = 10.0> class Bounded { public: Bounded() {}; Bounded(const Type& rhs) : val_(rhs) { if(rhs > Max || rhs < Min) throw logic_error("Out Of Bounds"); } operator Type () const { return val_; } Type val_; }; int main() { typedef Bounded<double, -10.0, 10.0> double_10; double_10 d(-4.2); cout << "d = " << d << "\n"; double d_prime = d; cout << "d_prime = " << d_prime << "\n"; double_10 d2(-42.0); cout << "d2 = " << d << "\n"; return 0; } 

Output:

 d = -4.2 d_prime = -4.2 
+1
source

Source: https://habr.com/ru/post/1435728/


All Articles