gpt4 book ai didi

c++ - 仅为具有 operator/defined 的此类 T 创建模板

转载 作者:太空狗 更新时间:2023-10-29 20:24:33 25 4
gpt4 key购买 nike

我想定义一个 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等没关系。但是如何防止使用复杂类型作为 T 如果他们没有 operator/operator+定义?

最佳答案

如果你想要一个不包含通过 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++ - 仅为具有 operator/defined 的此类 T 创建模板 <T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27607364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com