使用地图模板函数指针

Templating function pointers using Maps

本文关键字:函数 指针 地图      更新时间:2023-10-16

我正在尝试使用模板来创建一个理解概念的映射,但是我遇到了一个错误,未能理解我在做错了什么。

有人可以看看,让我知道我在做什么错吗?如果可能的话,请分享一个设计的示例,我真的很感激。

谢谢

#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;
}