c – 为什么不调用在构造函数中作为参数传递的自由函数?
发布时间:2020-12-16 10:07:56 所属栏目:百科 来源:网络整理
导读:为什么不是mystruct(plain_old_function);构造函数调用默认构造函数,而lambda调用专用的构造函数(mystruct(const std :: function std :: string() func))? 这可以使用吗? #include iostream#include functional#include stringstruct mystruct{ mystruct(
为什么不是mystruct(plain_old_function);构造函数调用默认构造函数,而lambda调用专用的构造函数(mystruct(const std :: function< std :: string()>& func))?
这可以使用吗? #include <iostream> #include <functional> #include <string> struct mystruct { mystruct() { std::cout << "Default construct :S" << std::endl; } mystruct ( const std::function< std::string() > &func ) { std::cout << func() << std::endl; } }; void callme ( const std::function< std::string() > &func ) { std::cout << func() << std::endl; } std::string free_function( ) { return "* Free function"; } int main() { std::cout << "Constructing with lambda:" << std::endl; mystruct( [](){ return "* Lambda function"; } ); std::cout << "Calling free function through another function:" << std::endl; callme( free_function ); std::cout << "Constructing with free function:" << std::endl; mystruct( free_function ); return 0; } Demo 输出: Constructing with lambda: * Lambda function Calling free function through another function: * Free function Constructing with free function: Default construct :S 解决方法
Vexing解析,
mystruct( free_function ); 被解析为 mystruct free_function; // declare a mystruct instance named free_function // (hiding the function) 你可以使用{}: mystruct{free_function}; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |