【发布时间】:2015-02-20 19:52:44
【问题描述】:
我想为类型定义一个template<T>,但我必须确保只有定义了operator/ 和operator+ 的类型才能作为T 传递。
这是因为我希望能够获得其中两个(属于同一类型)的插值,例如:
template<class T>
class Key final : public KeyBase{
public: //to keep the example simple
//unsigned timeMS; <-- iherited from KeyBase
T value;
public:
Key(unsigned timeMS, const T &value)
: KeyBase(timeMS), value(value){}
T inline getValue(){ return value; }
};
Key<float> start = {10, 5.0f};
Key<float> end = {15, 3.0f};
float ratioAtTime12 = 12 / (end.timeMS - start.timeMS);
float valueAtTime12 = start.value + (end.value - start.value) * ratio;
//Point2D is my own custom type that have operator+, - and / defined
Key<Point2D> start2 = {10, Point2D(10, 15)};
Key<Point2D> end2 = {15, Point2D(111, 6)};
...
Key<Character> start3 = {10, Character("Alan")}; //SHOULD generate an error
//because my custom Character type has no operator+, - or / defined!
对于float、int 等简单类型,没关系。但是,如果没有定义operator/ 和operator+,如何防止将复杂类型用作T?
【问题讨论】:
-
如果提到的运算符被用于未定义的类的实例上,则会出现编译错误。所以类型是隐式约束的。
-
如果没有定义这些操作符,你想让它做什么?
-
@GézaTörök 我同意。但是,我想在创建这样的对象的那一刻得到一个错误(从我的角度来看,甚至声明它是没有意义的),而不是等待操作员的使用。
-
@MarkB 我想最好生成一个编译时错误。