我想做这样的事情:
int a = 9, b = 3;
map<char,operator> m;
m['+'] = +;
m['-'] = -;
m['*'] = *;
m['/'] = /;
for(map<char,operator>::iterator it = m.begin(); it != m.end(); ++it) {
cout << func(a,b,it -> second) << endl;
}
输出是这样的:
12
6
27
3
我该怎么做?
我想做这样的事情:
int a = 9, b = 3;
map<char,operator> m;
m['+'] = +;
m['-'] = -;
m['*'] = *;
m['/'] = /;
for(map<char,operator>::iterator it = m.begin(); it != m.end(); ++it) {
cout << func(a,b,it -> second) << endl;
}
输出是这样的:
12
6
27
3
我该怎么做?
您可以在以下位置使用预制函子<functional>:
int a = 9, b = 3;
std::map<char, std::function<int(int, int)>> m;
m['+'] = std::plus<int>();
m['-'] = std::minus<int>();
m['*'] = std::multiplies<int>();
m['/'] = std::divides<int>();
for(std::map<char, std::function<int(int, int)>>::iterator it = m.begin(); it != m.end(); ++it) {
std::cout << it->second(a, b) << std::endl;
}
每个都是一个类,operator()它接受两个参数并返回对这两个参数进行数学运算的结果。例如,std::plus<int>()(3, 4)与 基本相同3 + 4。每个都存储为签名的函数包装对象,int(int, int)然后根据需要使用两个数字调用。