我如何做一个类的接口匹配双,但在哪个模板可以专门? [英] How do I make a class whose interface matches double, but upon which templates can be specialized?
本文介绍了我如何做一个类的接口匹配双,但在哪个模板可以专门?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何创建一个类的接口匹配double,但其模板类型不能动态转换为双精度类?
How do I make a class whose interface matches double, but whose templated types do not dynamic cast to double?
原因是我有一个运行时类型系统,我希望能够有类似double的类型:
The reason is that I have a run-time type system, and I want to be able to have a type that works just like double:
template<int min_value, int max_value>
class BoundedDouble: public double {};
然后使用模板专门化来获取有关该类型的运行时信息:
And then use template specialization to get run-time information about that 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 can't inherit from double...
推荐答案
您不能从本机类型派生。请改用组合:
You can't derive 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;
}
输出为:
d = -4.2
d_prime = -4.2
这篇关于我如何做一个类的接口匹配双,但在哪个模板可以专门?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文