c++ - 返回函数的函数是怎么个形式?
迷茫
迷茫 2017-04-17 12:58:41
0
2
630

书上说

函数可以直接返回一个可调用对象

可调用对象包括函数,函数指针等

所以函数可以直接返回一个函数。我怎么好像从来没见过?你们能举个例子给我看看吗?
还有函数返回lambda的例子

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
小葫芦
  1. A pointer to a function, such as

    int (*p)(int, int);

    p is a pointer to a function. This function has two parameters of type int and returns int.

  2. A function that returns a function pointer can be defined in the following two ways.

    • Direct definition

      int (*foo(char c))(int, int);
    • Use typedef

      typedef int OP(int, int);
      OP* foo(char c);

      The two methods are equivalent, and the second one is easier to see clearly.

    1. returns a pointer to the function.

  3. Application examples

    int foo_plus(int a, int b)
    {
      return a + b;
    }
    
    int foo_multiply(int a, int b)
    {
      return a * b;
    }
    
    typedef int OP(int, int);
    OP* foo(char c)
    {
       OP* p;
       switch(c) {
         case 'p':
           p = foo_plus;
           break;
         case 'm':
           p = foo_multiply;
           break;
         default:
           p = foo_multiply;
       }
       return p;
    }
    
    int main()
    {
      OP* f;
      int n;
      f = foo('p');
      n = f(1, 2);
      printf("%d", n); // 3
      f = foo('m');
      n = f(1, 2);
      printf("%d", n); // 2
      
      return 0;
    }

Supplement:
The function returns an object, which can be called.

A function object, that is, an object that overloads the bracket operator "()".
e.g.

class A{

public:
    int operator()(int x, int y)
    {
        return x + y;
    }

};
A a;
a(1, 2); has the same effect as foo_plus(1, 2); above.

Ty80

Callable objects mainly include function pointers, std::function and classes/structures that overload the meta bracket operator.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template