模板专门化,指定类型派生自某个类

问题描述 投票:0回答:1

我想专门研究下面示例中的 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,但我似乎无法让它工作。

c++ c++20 template-meta-programming
1个回答
0
投票

正如评论中提到的,您可以通过检测

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;
};
© www.soinside.com 2019 - 2024. All rights reserved.