【问题标题】:How declare lambda with function pointers (without auto)?如何用函数指针(没有自动)声明 lambda?
【发布时间】:2016-01-04 14:19:07
【问题描述】:

我可以在没有auto 的情况下轻松声明匿名函数(它们与 lambda 相同,但没有“上下文”-[...]):

#include <iostream>

using namespace ::std;

void foo(void (*f)(char))
{
    f('r');
}

int main()
{
    void (*anon)(char) = [](char c) -> void { cout << c << endl; };
    foo(anon);
    return 0;
}

但是如何声明 lambda 呢?这是唯一可能的方法吗? (也许使用 typedef)。这里我使用::std::function,但我没有在 foo 参数中的某处提到 f 的上下文...:

#include <iostream>
#include <functional>

using namespace ::std;

//int foo(auto f, char x) // !only since c++14
int foo(function<int(char)> f, char x)
{
    return f(x+1);
}

int main()
{
    int a = 5, b = 10;

    //void (*lambda)(char) = [](char c) { cout << c << endl; };
    //auto sample_lambda = [&a,b](char c) -> int // !only since c++11
    function<int(char)> sample_lambda = [&a,b](char c) -> int  
        {
            for (;a<b;a++)
                cout << a << c << endl;
            return (int)c+a; 
        };

    foo(sample_lambda, 's');
    return 0;
}

【问题讨论】:

  • 将 foo 定义为模板函数。 template&lt;class Function&gt; void foo(Function&amp;&amp; f) { f('r'); }
  • “声明一个 lambda”没有意义。 lambda 是 表达式 的一种类型,您不能删除表达式,就像“声明一个总和”或“声明一个函数调用”一样。
  • 非捕获 lambda 表达式可以衰减为指向函数的指针,但它不是指向函数的指针。

标签: c++ pointers lambda anonymous-function auto


【解决方案1】:

你不能。

闭包的类型是唯一的、未命名的类型。您的第一个示例有效,因为如果闭包类型没有捕获任何内容,则它们具有到指向函数的指针的转换函数,而不是因为闭包 void (*) (char)

您最好坚持使用auto,因为std::function 可能会为类型擦除带来额外开销。

【讨论】:

    【解决方案2】:

    auto作为参数是GCC等提供的扩展。你可以做的是使用模板:

    template<typename T>
    int callFoo(T funct, int x) {
        return funct(x+1);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 2020-04-13
      • 1970-01-01
      相关资源
      最近更新 更多