模板参数值的函数继承

在 C++ 中是否有可能根据模板参数的值从另一个类派生?

类似的东西:

template<std::uint8_t nbr>
class A :
    public B
{}

template<std::uint8_t nbr>
class A
{}

如果 nbr 大于 1,则 A 类派生自 B 类。如果 nbr = 0,则 A 类不是 B 类派生的。

如果是,我们该怎么做。我检查了 type_traits 但我没有找到。

回答

您可能会为此使用专业化:

template<std::uint8_t nbr>
class A : public B
{};

template<>
class A<0>
{};

std::conditional 也可能有帮助

struct Empty{};

template<std::uint8_t nbr>
class A : public std::conditional_t<nbr == 0, Empty, B>
{};

  • @largest_prime_is_463035818: From [EBO](https://en.cppreference.com/w/cpp/language/ebo), since C++11, EBO is mandatory for [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType) (which A is actually (in that simplified example)).

以上是模板参数值的函数继承的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>