我正在尝试创建std::function一个移动捕获lambda表达式.请注意,我可以创建一个移动捕获lambda表达式而不会出现问题; 只有当我尝试将其包装成一个std::function我得到错误时.
例如:
auto pi = std::make_unique<int>(0);
// no problems here!
auto foo = [q = std::move(pi)] {
*q = 5;
std::cout << *q << std::endl;
};
// All of the attempts below yield:
// "Call to implicitly-deleted copy constructor of '<lambda...."
std::function<void()> bar = foo;
std::function<void()> bar{foo};
std::function<void()> bar{std::move(foo)};
std::function<void()> bar = std::move(foo);
std::function<void()> bar{std::forward<std::function<void()>>(foo)};
std::function<void()> bar = std::forward<std::function<void()>>(foo);
Run Code Online (Sandbox Code Playgroud)
我会解释为什么我要写这样的东西.我写了一个UI库,类似于jQuery的或JavaFX的,允许用户通过传递给处理鼠标/键盘事件std::functions到方法有相似的名字on_mouse_down(),on_mouse_drag(),push_undo_action(),等.
显然,std::function我想要传入的理想情况下应该使用移动捕获lambda表达式,否则我需要求助于我在C++ 11作为标准时使用的丑陋的"release/acquire-in-lambda"习语:
std::function<void()> baz = …Run Code Online (Sandbox Code Playgroud) Boost Hana提供了以简单而美观的方式对类成员字段进行内省的能力:
// define:
struct Person {
std::string name;
int age;
};
// below could be done inline, but I prefer not polluting the
// declaration of the struct
BOOST_HANA_ADAPT_STRUCT(not_my_namespace::Person, name, age);
// then:
Person john{"John", 30};
hana::for_each(john, [](auto pair) {
std::cout << hana::to<char const*>(hana::first(pair)) << ": "
<< hana::second(pair) << std::endl;
});
Run Code Online (Sandbox Code Playgroud)
但是,文档仅提及成员字段.我也想对方法进行反思.我试图用一种方法天真地扩展示例:
struct Foo {
std::string get_name() const { return "louis"; }
};
BOOST_HANA_ADAPT_STRUCT(::Foo, get_name);
Run Code Online (Sandbox Code Playgroud)
这编译.但是,只要我尝试使用它,使用类似于上面的代码(for_each...),我就会遇到很多编译错误.由于没有显示方法内省的例子,我想知道它是否得到支持.
我观察到对于以下功能
def foo(x: int) -> List[int]:
return x + 1
Run Code Online (Sandbox Code Playgroud)
可以使用表达式获取注释信息foo.__annotations__,结果为{'x': <class 'int'>, 'return': typing.List[int]}。
这是官方API吗?如果没有,是否存在官方 API 来获取对象的签名,如果有,它是什么?