c – 仅为具有运算符/已定义的T创建模板

我想定义一个模板< T>对于类型,但我必须确保只有具有运算符/和运算符定义的类型才能作为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等简单类型,没关系.但是,如果没有运算符/和运算符定义,如何防止将复杂类型用作T?

解决方法:

如果您想要一个不包含通过ADL等找到的数十个运算符的错误消息,您可以定义特征:

template <typename, typename=void>
struct isAddable : std::false_type {};

template <typename T>
struct isAddable<T, decltype(void(std::declval<T>() + std::declval<T>()))>
    : std::true_type {};

template <typename, typename=void>
struct isDividable : std::false_type {};

template <typename T>
struct isDividable<T, decltype(void(std::declval<T>() / std::declval<T>()))>
    : std::true_type {};

…并使用静态断言.

static_assert( isAddable<T>{} && isDividable<T>{}, "Invalid T!" );

或者,要获得更具体的信息:

static_assert( isAddable<T>{}, "T not addable!" );
static_assert( isDividable<T>{}, "T not dividable!" );

Demo.

您还可以使用方便的宏来定义此类特征.

#define VAL std::declval<T>()

#define DEF_TRAIT(name, expression)                                  \
template <typename, typename=void> struct name : std::false_type {}; \
template <typename T>                                                \
struct name<T, decltype(void(expression))> : std::true_type {};

DEF_TRAIT(isDividable, VAL / VAL)
DEF_TRAIT(isAddable, VAL + VAL)

Demo.

上一篇:c# – “x as X!= null”和“x is X”总是返回相同的结果?


下一篇:java – 在switch中使用关系运算符