【发布时间】:2021-09-24 19:25:53
【问题描述】:
我正在尝试实现一个从基模板继承的派生类,并将派生类作为其模板参数(希望下面的示例能够解决问题):
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。
【问题讨论】:
标签: c++ templates c++-concepts incomplete-type