TS 概念类型名约束

TS Concepts typename constraint

本文关键字:约束 类型 TS      更新时间:2023-10-16

我试图使用概念作为子类的约束(由gcc使用gnu2a和fconcepts编译(来制作一个简单的模板化继承示例。我希望下面的示例可以很好地编译,但我无法让它工作:

template<class structure>
concept bool Has_Type() {return requires{
typename structure::type;
};}
template<class sub> requires Has_Type<sub>()
struct structure {
//using type = typename sub::type;
};
struct child: structure<child> {
using type = child;
};

这个概念抛出了一个错误,说typename structure::type would be ill-formed.我不明白为什么,因为孩子有一个可以通过::运算符访问的类型。我尝试了这个例子,看看这个想法本身是否有效,这编译并运行良好:

struct child {
using type = child;
};
template<class it>
auto func() {
typename it::type f = child();
return 0;
}
// in a test.cpp file
auto g = func<child>();

这让我认为这个想法得到了支持,所以我不确定为什么这个概念失败了。有人知道为什么吗?

这是因为child在这一点上是不完整的。[class.mem]p6 说:

类在 类说明符。

后跟一些例外(例如不在成员函数中(。但是在基句中,它是不完整的,因此成员typeHas_Type不可用。