【发布时间】:2019-02-26 23:19:47
【问题描述】:
我正在学习函数指针和映射。我必须使用函数指针和映射来编写 switch 语句的复制而不使用 if 或 switch。
我想编写一个函数 execute(),它接受两个参数“a”和“b”,并使用适当的操作字符进行操作。
#include <iostream>
#include <string>
#include <map>
using namespace std;
// define the function pointer fptr, templated
template <typename T>
using fptr = T(*)(T, T);
template <typename T>
T plus(T a, T b){
return a + b;
}
template <typename T>
T minus(T a, T b){
return a - b;
}
template <typename T>
T multiply(T a, T b){
return a * b;
}
template <typename T>
T divide(T a, T b){
return a / b
}
// Call back the function pointer on two variables
template <typename T>
T operation(fptr<T> f, T a, T b){
f(a, b);
}
// Execute map to fit an operation character to an operation function pointer
template <typename T>
T execute(T a, T b, char c){
std::map<char, fptr<T> > m;
m['+'] = +
m['-'] = −
m['*'] = &multiply;
m['/'] = ÷
return operation(m[c], a, b);
}
int main(){
execute<int>(1, 2, '+');
execute<double>(1.2, 3.4, '/');
}
以下是我得到的错误。我在回电中没有错别字,但错误仍然模棱两可。我想知道为什么会这样。我真的很感激这些建议。非常感谢!
error: reference to 'plus' is ambiguous
m['+'] = +
^
note: candidate found by name lookup is 'plus'
T plus(T a, T b){
^
note: candidate found by name lookup is 'std::__1::plus'
struct _LIBCPP_TEMPLATE_VIS plus : binary_function<_Tp, _Tp, _Tp>
^
error: reference to 'minus' is ambiguous
m['-'] = −
^
note: candidate found by name lookup is 'minus'
T minus(T a, T b){
^
note: candidate found by name lookup is 'std::__1::minus'
struct _LIBCPP_TEMPLATE_VIS minus : binary_function<_Tp, _Tp, _Tp>
^
【问题讨论】:
-
试试
&plus<T>。 -
@jarod42:不幸的是它不起作用:(
标签: c++ dictionary templates