当我阅读 std::function 时,我发现以下语法令人困惑。直接跟在空括号后面的结构在这里做什么?它等效于声明一个结构对象并调用其运算符。
#include <iostream>
using namespace std;
int main() {
struct F {
bool operator()(int a) {
return a>0;
}
};
function<bool(int)> f = F(); //What does the syntax F() mean here?
struct F ff;
cout << f(1) <<endl;
cout << ff(1) <<endl;
return 0;
}
最佳答案
What does the syntax F() mean here?
意思是构造一个F
类型的对象使用默认构造函数。
A std::function
可以使用满足其调用条件的任何可调用对象来构造。在您的特定用例中,F
的一个实例符合 std::function<bool(int)>
的标准.因此,
function<bool(int)> f = F();
是构造 f
的有效语句.
关于C++ struct直接跟括号组成仿函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38062118/