受限CRTP过早拒绝

问题描述

我正在尝试实现一个从基模板继承的派生类,并将派生类作为其模板参数(希望下面的示例可以解决问题):

template <class T>
struct S
{
    T f() {return T();}
};

struct D : public S<D>
{
};

这也可以在 gcc、clang 和 msvc 上编译并运行良好。现在,我想“确保”模板参数继承自基类:

#include <concepts>

template <class T>
concept C
= requires ( T t )
{
    { t.f() };
};

template <C T>
struct S
{
    T f() {return T();}
};

struct D : public S<D>
{
};

然而,这被每个编译器拒绝,clang 提供了最多的洞察力:

error: constraints not satisfied for class template 'S' [with T = D]
struct D : public S<D>
                  ^~~~
note: because 'D' does not satisfy 'C'
template <C T>
          ^
note: because 't.f()' would be invalid: member access into incomplete type 'D'
    { t.f() };

我了解编译器的来源:D 在必须检查约束时尚未完全定义,因此它失败以代替必要的信息。也就是说,我有点失望,在评估尚未检查的约束之前,没有尝试完成派生类的定义。

这是有意为之吗?有没有其他方法可以检查实际工作的继承?

顺便说一下,在这种情况下,gcc 给出了一个相当无用的 error message

解决方法

可以在基类的默认构造函数中查看需求

#include <type_traits>

template<class Derived>
class Base
{
public:
    Base()
    {
        static_assert(std::is_base_of_v<Base<Derived>,Derived>);
    }
};

class Derived : public Base<Derived>
{ };

这也必须在任何其他用户定义的非复制和非移动 base 构造函数中进行检查。这是有效的,因为 Derived 在实例化构造函数时已完全定义。