簡體   English   中英

C ++概念:一些簽名函數轉換

[英]C++ concepts: Some signatures function conversion

不幸的是,我發現的關於concepts的唯一教程是lite lite教程(它實際上是基本的)。 即使使用了技術規范,也有一些我不知道如何將其轉換為概念的簽名功能( 也許只是因為我的英語不好並且我不能很好地閱讀技術規范 )。

因此,有一個簽名函數列表,我仍然不知道如何“ 翻譯 ”:

CFoo->類CFoo {};

  • void Foo1() const;
  • CFoo& Foo2();
  • void Foo3(CFoo&);
  • {static, friend, ... } void Foo4();
  • template < typename ... Args > void Foo5(Args && ... args);

我想為具有這些功能的類提供某種接口。 甚至不知道這是否可能。 Foo2和Foo3似乎是相同的問題。


老實說,我真的很想知道Foo2和Foo5。

我為Foo2嘗試了一些東西,但對Foo5卻一無所知:

class Handle {};

template < typename Object >
concept bool C_Object =
  requires(Handle handle) {
    {get(handle)} -> Object&
  };

template < C_Object Object >
class Foo {

  Object obj;
};

int main() {

  Foo<int>  test;
  return 0;
}

我知道這不會編譯,因為Foo沒事,但是這些不是正確的錯誤:

Test1.cpp:6:16: error: there are no arguments to ‘get’ that depend on a template parameter, so a declaration of ‘get’ must be available [-fpermissive]
     {get(handle)} -> Object&
                ^
Test1.cpp:6:16: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)
Test1.cpp: In function ‘int main()’:
Test1.cpp:18:10: error: template constraint failure
   Foo<int>  test;
          ^
Test1.cpp:18:10: note:   constraints not satisfied
Test1.cpp:4:14: note: within ‘template<class Object> concept const bool C_Object<Object> [with Object = int]’
 concept bool C_Object =
              ^~~~~~~~
Test1.cpp:4:14: note:     with ‘Handle handle’
Test1.cpp:4:14: note: the required expression ‘get(handle)’ would be ill-formed

如果有人可以向我指出一些資源,或者為什么不提供解決方案。 這將會非常棒。

祝你有美好的一天

我知道這不會編譯,因為Foo沒事[…]

概念處理正則表達式。 特別地, requires表達式的范圍是普通范圍,而不是類范圍。 這個概念可能更明顯:

template<typename Lhs, typename Rhs>
concept bool Addable = requires(Lhs lhs, Rhs rhs) {
    lhs + rhs;
};

因為給定int lhs; long rhs;所以實現了Addable<int, long> int lhs; long rhs; int lhs; long rhs; 那么lhs + rhs是有效的表達式。 我們在參數列表中顯式引入的兩個(假裝)變量上使用內置加法運算符,而不是對隱式*this調用成員operator+

概念是關於廣義的接口(如“ API”),而不是狹義的OOP。 您可以將Addable視為類型對上的關系。 Addable<int, long>持有並不意味着intAddable有特殊的關系。 確實可以將Addable用作例如

template<Addable<long> Var>
struct client {
    Var var;
};

然后client<int>帶有Addable<int, long>約束,但是此快捷方式本質上是語法上的。 這是減少樣板的有用方法,即避免讓我們編寫template<typename Var> requires Addable<Var, long>

考慮到這一點,這里有一些表達式可能很接近檢查您提到的成員簽名以及Handle場景:

template<typename Obj>
concept bool Object = requires(Obj obj, Obj const cobj, Handle handle) {
    cobj.Foo1();
    { obj.Foo2() } -> Obj&;
    obj.Foo3(obj);
    // static
    Obj::Foo4();
    // non-member, possibly friend
    Foo4(obj);

    { obj.get(handle) } -> Obj&;
};

(我Foo5Foo5場景,因為這是值得回答的問題,這里是一個線索 。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM