람다를 클래스 멤버로 정의 할 수 있습니까?
예를 들어, 함수 객체 대신 람다를 사용하여 아래 코드 샘플을 다시 작성할 수 있습니까? ?
struct Foo {
std::function<void()> bar;
};
내가 궁금한 이유는 다음 람다가 인수로 전달 될 수 있기 때문입니다.
template<typename Lambda>
void call_lambda(Lambda lambda) // what is the exact type here?
{
lambda();
}
int test_foo() {
call_lambda([]() { std::cout << "lambda calling" << std::endl; });
}
람다가 함수 인수로 전달 될 수 있으면 멤버 변수로도 저장 될 수 있다고 생각했습니다.
좀 더 땜질을 한 후에 이것이 효과가 있다는 것을 발견했습니다 (하지만 그것은 무의미합니다) :
auto say_hello = [](){ std::cout << "Hello"; };
struct Foo {
typedef decltype(say_hello) Bar;
Bar bar;
Foo() : bar(say_hello) {}
};
Лямбда просто создает функциональный объект, так что, да, вы можете инициализировать элемент функции с помощью лямбды. Вот пример:
#include <functional>
#include <cmath>
struct Example {
Example() {
lambda = [](double x) { return int(std::round(x)); };
};
std::function<int(double)> lambda;
};
#include <functional>
struct Foo {
std::function<void()> bar;
};
void hello(const std::string & name) {
std::cout << "Hello " << name << "!" << std::endl;
}
int test_foo() {
Foo f;
f.bar = std::bind(hello, "John");
// Alternatively:
f.bar = []() { hello("John"); };
f.bar();
}