我想专门研究下面示例中的 NumberValue 类。
class Number {};
class One: public Number {
static constexpr int value = 1;
};
class Two: public Number {
static constexpr int value = 2;
};
class Three: public Number {
static constexpr int value = 3;
};
class NotANumber {};
template <typename T>
struct NumberValue {
static constexpr int value = -1;
};
/* Need some template specialization here for classes derived from Number */
static_assert(NumberValue<std::string>::value == -1);
static_assert(NumberValue<NotANumber>::value == -1);
static_assert(NumberValue<One>::value == 1);
static_assert(NumberValue<Two>::value == 2);
static_assert(NumberValue<Three>::value == 3);`
我尝试了一个带有概念的解决方案,enable_if,is_base_of,但我似乎无法让它工作。
正如评论中提到的,您可以通过检测
value
是否源自NumberValue
来将T::value
的T
设置为Number
。标准中相应的概念是std::derived_from
。
template <typename T>
struct NumberValue {
static constexpr int value = -1;
};
template <std::derived_from<Number> T>
struct NumberValue<T> {
static constexpr int value = T::value;
};