当前位置:优学网  >  在线题库

从函数C返回函数对象++

发表时间:2022-07-22 00:33:20 阅读:106

让以下函数:

returntype Foo(void(*bar)(const C&));

为了让Foo返回传递的函数__ functor aka bar,应该插入什么而不是returntype

🎖️ 优质答案
  • 直接方法如下

    void ( *Foo(void(*bar)(const C&)) ( const C & );
    

    或者可以使用using或typedef别名,如

    using Fp = void ( * )( const C & );
    
    or 
    
    typedef void ( *Fp )( const C & );
    

    在那之后

    Fp Foo( Fp bar );
    
  • &ltH4和gt方法1和lt/h4和gt

    C++11的一个选项是在返回类型中使用占位符类型autodecltype,使用尾部返回类型语法,如下所示:

    auto Foo(void(*bar)(const C&)) -> decltype(bar); //this is more readable than method 2 below
    

    &lth4和gt方法2和lt/h4和gt

    void (*Foo(void(*bar)(const C&)))(const C&); //less readable than method 1 above
    

    如我们所见,方法1比方法2更具可读性.

  • 假设您有一个函数void bar(const C&amp),并考虑Foo(bar).

    为了调用返回的函数指针,需要首先对其进行解引用,(*Foo(bar)),然后向其传递一个const C&amp(将其称为"the_C"):

    (*Foo(bar))(the_c)
    

    由于fn返回void,您现在可以填写以下类型:

        void (*Foo(void(*bar)(const C&)))(const C&)
          ^        ^                  ^      ^
          |        |<-  parameter   ->|      | parameter for the returned function       
          |
     Ultimate result
    

    或者,你可以决定不放弃你的理智,并命名类型:

    
    using function = void(*)(const C&);
    function Foo(function bar);
    
  • 相关问题