相关疑难解决方法(0)

将捕获lambda作为函数指针传递

是否可以将lambda函数作为函数指针传递?如果是这样,我必须做错了,因为我收到编译错误.

请考虑以下示例

using DecisionFn = bool(*)();

class Decide
{
public:
    Decide(DecisionFn dec) : _dec{dec} {}
private:
    DecisionFn _dec;
};

int main()
{
    int x = 5;
    Decide greaterThanThree{ [x](){ return x > 3; } };
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译它时,我得到以下编译错误:

In function 'int main()':
17:31: error: the value of 'x' is not usable in a constant expression
16:9:  note: 'int x' is not const
17:53: error: no matching function for call to 'Decide::Decide(<brace-enclosed initializer list>)'
17:53: note: candidates are: …
Run Code Online (Sandbox Code Playgroud)

c++ lambda function-pointers c++11

186
推荐指数
4
解决办法
12万
查看次数

C++ 11中的递归lambda函数

我是C++ 11的新手.我正在编写以下递归lambda函数,但它不编译.

sum.cpp

#include <iostream>
#include <functional>

auto term = [](int a)->int {
  return a*a;
};

auto next = [](int a)->int {
  return ++a;
};

auto sum = [term,next,&sum](int a, int b)mutable ->int {
  if(a>b)
    return 0;
  else
    return term(a) + sum(next(a),b);
};

int main(){
  std::cout<<sum(1,10)<<std::endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译错误:

vimal @ linux-718q:〜/ Study/09C++/c ++ 0x/lambda> g ++ -std = c ++ 0x sum.cpp

sum.cpp:在lambda函数中:sum.cpp:18:36:错误:' ((<lambda(int, int)>*)this)-><lambda(int, int)>::sum'不能用作函数

gcc版本

gcc版本4.5.0 20091231(实验性)(GCC)

但如果我改变sum()下面的声明,它的作用是:

std::function<int(int,int)> sum = [term,next,&sum](int a, …
Run Code Online (Sandbox Code Playgroud)

c++ lambda c++11

127
推荐指数
8
解决办法
6万
查看次数

C++ Lambda的内存布局

为了更好地理解C++ lambdas的实现,我欺骗了编译器将lambda视为一个对象,似乎它们在内存中的布局相同.

注意:这只是为了澄清,我不是在提倡在生产中编写这些类型的黑客

这是由语言规范还是编译器实现细节保证的?

struct F
{
    int a;  int b;  int c;
    void printLambdaMembers()
    {
        cout << this << endl; // presumably the lambda 'this'
        cout << a << endl; // prints 5   
        cout << b << endl;
        cout << c << endl;
    }
};

void demo()
{
    int a = 5;
    int b = 6;
    int c = 7;
    auto lambda = [a,b,c]() { cout << "In lambda!\n";  };
    // hard cast the object member function pointer …
Run Code Online (Sandbox Code Playgroud)

c++ lambda

3
推荐指数
1
解决办法
183
查看次数

标签 统计

c++ ×3

lambda ×3

c++11 ×2

function-pointers ×1