不能从本机类型派生。改为使用合成:
#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