【问题标题】:Writing a recursive base class concept in C++用 C++ 编写递归基类概念
【发布时间】:2021-01-21 09:22:15
【问题描述】:

在 C++ 中,我想将 Foo<T> 类的模板参数 T 严格限制为 Foo<T> 的继承者。为此,我写了以下内容:

template <typename TSelf> class Foo;

template <typename TSelf>
  requires (is_base_of<Foo<TSelf>, TSelf>)
class Foo
{
};

我得到的错误是

'Foo': requires clause is incompatible with the declaration

我该如何解决这个问题?

【问题讨论】:

  • 你不能。即使此错误已解决,这也不是首发。检查可派生性需要完全定义的对象类型。因此class A : Foo&lt;A&gt; ... 总是格式错误的。
  • @Dmitri Nesteruk 在不相关的说明中,感谢您在 PluralSight 上制作这些视频 :)
  • @StoryTeller-UnslanderMonica 谢谢,有什么解决方法吗?我猜static_assert 也不起作用?
  • @M.A 非常感谢!

标签: c++ templates constraints c++20 c++-concepts


【解决方案1】:

在 CRTP 中,派生类是不完整的。

您可以在应该调用的方法中添加该断言,作为析构函数:

template <typename TSelf>
class Foo
{
    // ...
    ~Foo() { static_assert(std::is_base_of_v<Foo<TSelf>, TSelf>); }
    // ...
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-23
    • 2016-07-17
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 2019-11-06
    相关资源
    最近更新 更多