C++概念:CRTP
这可能只是该概念不好,但我不明白为什么。并没有找到任何与构造函数的例子。或者,也许它没有任何关系的构造......C++概念:CRTP
template < typename T >
concept bool C_Object() {
return requires {
T();
};
}
template < C_Object Object>
class DefaultManager {
// Content;
};
template < C_Object Derived >
class Component {
// Content
};
struct Test : public Component<Test> {
int data;
Test() = default;
};
int main() {
Test test;
return 0;
}
给错误:
test2.cpp:21:36: error: template constraint failure
struct Test : public Component<Test> {
^
test2.cpp:21:36: note: constraints not satisfied
test2.cpp:2:14: note: within ‘template<class T> concept bool C_Object() [with T = Test]’
concept bool C_Object() {
^~~~~~~~
test2.cpp:2:14: note: the required expression ‘T()’ would be ill-formed
这听起来像一个:“嘿,我的代码是坏了,请修复它”,对不起。
反正感谢
有一个伟大的日子
的问题是在这里:
struct Test : public Component<Test> {
每当你这么多名约束类模板的专业化,给定参数根据约束进行验证。在这种情况下,这意味着C_Object<Test>
被检查满意,但由于Test
不完整 - 编译器尚未解析其定义 - C_Object
未得到满足。
这是CRTP基础的经典问题的“概念”版本:您必须延迟对派生类的检查,直到其定义完成。
-10分为C++ :( –
我甚至不知道CRTP。我觉得这个晚上太多了 如果你足够疯狂我喜欢解释:) 但是无论如何,我真的很幸运,你在那里。 PS:我会在阅读关于CRTP和东西(明天)时关闭这个问题。 –
即使在StackOverflow上:https://stackoverflow.com/questions/19886041/will-concepts-lite-change-the-need-of-crtp-to-achieve-static-polymorphism?rq=1 我没有找到为什么我的代码不工作,CRTP似乎没问题(没有概念就完美了)。如你所说,我必须延迟派生类的检查,但是找不到任何有关这方面的信息。 –
你知道概念没有达到标准吗? – SergeyA
@SergeyA是可能C++ 20 –