使用地图模板函数指针
Templating function pointers using Maps
我正在尝试使用模板来创建一个理解概念的映射,但是我遇到了一个错误,未能理解我在做错了什么。
有人可以看看,让我知道我在做什么错吗?如果可能的话,请分享一个设计的示例,我真的很感激。
谢谢
#include <iostream>
#include <map>
using namespace std;
enum MathOperations
{
ADD = 0,
SUBTRACT,
MULTIPLY,
DIVISION
};
template <typename T>
T Addition(T a, T b)
{
return a + b;
}
template <typename T>
T Subtraction(T a, T b)
{
return a - b;
}
template <typename T>
struct MathOp
{
typedef T (*FuncPtr) (T, T);
};
/* I am getting a warning here, which says variable templates are c++1 extension */
template <typename T>
const std::map<MathOperations, typename MathOp<T>::FuncPtr> MathMap = {
{ MathOperations::ADD, &Addition<T> },
{ MathOperations::SUBTRACT, &Subtraction<T> }
};
int main ()
{
MathOp<int> mathIntObj;
/* I am getting error here */
/* No viable overloaded operator[] for type 'const std::map<MathOperations, typename MathOp<int>::FuncPtr>' */
std::cout << *(MathMap<int>[MathOperations::ADD])(1, 2) << endl;
return 0;
}
编辑:感谢@piotr Skotnicki,他分享了我的错误解决方案。我必须进行以下更改:
std::cout << (*MathMap<int>.at(MathOperations::ADD))(1, 2) << endl;
删除
MathOp<int> mathIntObj;
仍然,我需要修复警告。有任何想法吗 ?谢谢
为什么不使用lambdas和类模板std::function
,从而大大降低了您的代码大小:
#include <iostream>
#include <map>
#include <functional>
using namespace std;
enum MathOperations
{
ADD = 0,
SUBSTRACT,
MULTIPLY,
DIVISION
};
template <typename T>
const std::map<MathOperations, typename std::function<T(T,T)>> MathMap = {
{ MathOperations::ADD, [](T a, T b){ return a + b; } },
{ MathOperations::SUBSTRACT, [](T a, T b) { return a - b; } }
};
int main ()
{
std::cout << (MathMap<int>.at(MathOperations::ADD))(3, 2) << endl;
std::cout << (MathMap<int>.at(MathOperations::SUBSTRACT))(6, 5) << endl;
return 0;
}
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针