我在开始了解 C++20 概念时遇到一些困难。我想定义一个概念,要求类有一个名为的成员,count_该成员必须是类型int:
#include <concepts>\n\ntemplate <typename T>\nconcept HasCount = requires(T thing) {\n { thing.count_ } -> std::same_as<int>;\n};\nRun Code Online (Sandbox Code Playgroud)\n以下结构应该满足这个概念:
\nstruct BaseTableChunk {\n BaseTableChunk* next_;\n int count_ = 0;\n int data_[1000];\n};\nRun Code Online (Sandbox Code Playgroud)\n然后,以下代码无法编译:
\ntemplate <HasCount Chunk>\nclass BaseTable {\n void doSomething();\n};\n\nint main() {\n BaseTable<BaseTableChunk> table{};\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n编译器给出以下错误:
\nnote: 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)