How do I make a class whose interface matches double, but upon which templates can be specialized?

前端 未结 1 1460
天涯浪人
天涯浪人 2021-01-24 01:35

How do I make a class whose interface matches double, but whose templated types do not dynamic cast to double?

The reason is that I have a run-time type system, and I wa

1条回答
  •  面向向阳花
    2021-01-24 02:08

    You can't derive from native types. Use composition instead:

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    template 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;
        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;
    }
    

    The output is:

    d = -4.2
    d_prime = -4.2
    

    0 讨论(0)
提交回复
热议问题