小编E_3*_*E_3的帖子

需要特定成员返回类型的概念

我在开始了解 C++20 概念时遇到一些困难。我想定义一个概念,要求类有一个名为的成员,count_该成员必须是类型int

\n
#include <concepts>\n\ntemplate <typename T>\nconcept HasCount = requires(T thing) {\n    { thing.count_ } -> std::same_as<int>;\n};\n
Run Code Online (Sandbox Code Playgroud)\n

以下结构应该满足这个概念:

\n
struct BaseTableChunk {\n    BaseTableChunk* next_;\n    int count_ = 0;\n    int data_[1000];\n};\n
Run Code Online (Sandbox Code Playgroud)\n

然后,以下代码无法编译:

\n
template <HasCount Chunk>\nclass BaseTable {\n    void doSomething();\n};\n\nint main() {\n    BaseTable<BaseTableChunk> table{};\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

编译器给出以下错误:

\n
note: constraints not satisfied\nIn file included from /usr/include/c++/10/compare:39,\n                 from /usr/include/c++/10/bits/stl_pair.h:65,\n                 from /usr/include/c++/10/bits/stl_algobase.h:64,\n                 from /usr/include/c++/10/bits/char_traits.h:39,\n                 from /usr/include/c++/10/ios:40,\n                 from /usr/include/c++/10/ostream:38,\n                 from /usr/include/c++/10/iostream:39,\n                 from Minimal2.cxx:1:\n/usr/include/c++/10/concepts:57:15:   required for the …
Run Code Online (Sandbox Code Playgroud)

c++ c++-concepts c++20

12
推荐指数
1
解决办法
1277
查看次数

标签 统计

c++ ×1

c++-concepts ×1

c++20 ×1