lambda对于有捕获和无捕获的展开有比较大的区别,无捕获的情况下会多两个函数,可以分别看下面代码的Foo
和Bar
。
Link: https://cppinsights.io/s/8c06a095
cpp#include <iostream>
#include <functional>
struct Foo { // lambda with captures
void operator()() {
std::cout << "Foo@" << __func__ << ":" << __LINE__ << std::endl;
}
};
struct Bar { // lambda without captures
using fun_t = void(*)();
void operator()() {
std::cout << "Bar@" << __func__ << ":" << __LINE__ << std::endl;
}
static void invoke() {
Bar{}.operator()();
}
operator fun_t() {
return invoke;
}
};
struct FooBar {
using fun_t = void(*)();
static void invoke() {
std::cout << "FooBar@" << __func__ << ":" << __LINE__ << std::endl;
}
operator fun_t() {
return invoke;
}
void operator()() {
std::cout << "FooBar@" << __func__ << ":" << __LINE__ << std::endl;
}
void operator()(int) {
std::cout << "FooBar@" << __func__ << ":" << __LINE__ << std::endl;
}
};
int main(int argc, char **argv) {
using fun_t = void(*)();
Foo foo;
foo();
Bar bar;
bar();
FooBar fb;
fb();
fun_t f = fb;
f();
std::function<void()> func_c = f;
f();
std::function<void()> func = fb;
func();
std::function<void(int)> func_int = fb;
func_int(0);
return 0;
}
Output:
gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.2)
std=c++17
Foo@operator():6 Bar@operator():13 FooBar@operator():32 FooBar@invoke:26 FooBar@invoke:26 FooBar@operator():32 FooBar@operator():35
operator ()
和operator fun_t
同时定义的情况下,直接调用对象或者使用function
包装器来调用对象的结果一致,都是优先使用operator ()
。
本文作者:OhtoAi
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!