gpt4 book ai didi

c++ - TS Concepts 类型名约束

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:33:52 24 4
gpt4 key购买 nike

我正在尝试使用一个概念作为对子类的约束(由 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 的格式不正确。我不明白为什么,因为 child 具有 :: 运算符可访问的类型。我尝试了这个例子来查看这个想法本身是否有效,并且编译并运行良好:

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 说:

A class is considered a completely-defined object type (6.7) (or complete type) at the closing } of the class-specifier.

紧随其后的是一些异常(exception)情况(比如不在成员函数中)。但是在 base-clause 中,它是不完整的,因此成员 typeHas_Type 不可用。

关于c++ - TS Concepts 类型名约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51126604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com