简体   繁体   English

带有特定参数的函数的c ++指针向量

[英]c++ vector of pointers to functions with specific parameters

if I have a function and I want to make a pointer to it with a specific parameter I can use auto but like this: 如果我有一个函数,并且想要使用特定参数指向它,我可以使用auto,但是像这样:

void bar(int n){std::cout << n;}
auto foo = std::bind(bar, 2);

but if I want to make a vector of these pointers it doesn't work 但是,如果我想对这些指针进行向量处理,那是行不通的

std::vector<auto> v;

You could write vector<decltype(foo)> v; 您可以编写vector<decltype(foo)> v; although that probably doesn't do what you want (other bind expressions may give incompatible types). 尽管这可能无法满足您的要求(其他bind表达式可能会提供不兼容的类型)。

As mentioned in comments, std::function is designed for this purpose: 如评论中所述, std::function是为此目的而设计的:

std::vector< std::function<void()> > v;

v.emplace_back( foo );
v.emplace_back( std::bind(bar, 2) );
v.emplace_back( []{ std::cout << 2; } );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM