如何创建一个接口匹配为double的类,但是哪些模板可以专用?

时间:2010-06-17 02:40:52

标签: c++ inheritance templates

如何创建一个接口匹配为double的类,但其模板类型不会动态转换为double?

原因是我有一个运行时类型系统,我希望能够有一个类似double的类型:

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

然后使用模板特化来获取有关该类型的运行时信息:

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. }

但是,你不能继承双重......

1 个答案:

答案 0 :(得分:2)

您无法从本机类型派生。改为使用构图:

#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;
}

输出结果为:

d = -4.2
d_prime = -4.2