2016-11-28 202 views
3

這可能只是該概念不好,但我不明白爲什麼。並沒有找到任何與構造函數的例子。或者,也許它沒有任何關係的構造......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 

這聽起來像一個:「嘿,我的代碼是壞了,請修復它」,對不起。

反正感謝

有一個偉大的日子

+1

你知道概念沒有達到標準嗎? – SergeyA

+0

@SergeyA是可能C++ 20 –

回答

5

的問題是在這裏:

struct Test : public Component<Test> { 

每當你這麼多約束類模板的專業化,給定參數根據約束進行驗證。在這種情況下,這意味着C_Object<Test>被檢查滿意,但由於Test不完整 - 編譯器尚未解析其定義 - C_Object未得到滿足。

這是CRTP基礎的經典問題的「概念」版本:您必須延遲對派生類的檢查,直到其定義完成。

+0

-10分爲C++ :( –

+0

我甚至不知道CRTP。我覺得這個晚上太多了 如果你足夠瘋狂我喜歡解釋:) 但是無論如何,我真的很幸運,你在那裏。 PS:我會在閱讀關於CRTP和東西(明天)時關閉這個問題。 –

+0

即使在StackOverflow上:https://stackoverflow.com/questions/19886041/will-concepts-lite-change-the-need-of-crtp-to-achieve-static-polymorphism?rq=1 我沒有找到爲什麼我的代碼不工作,CRTP似乎沒問題(沒有概念就完美了)。如你所說,我必須延遲派生類的檢查,但是找不到任何有關這方面的信息。 –