使用Maps的模板函数指针

时间:2017-03-09 08:56:42

标签: c++ function templates stl function-pointers

我正在尝试使用模板来创建用于理解概念的映射,但是我收到错误并且无法理解我做错了什么。

任何人都可以看看,让我知道我做错了什么?如果可能的话,请分享一个设计的工作示例,我真的很感激。

由于

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

仍然,我需要修正警告。有任何想法吗 ?谢谢

1 个答案:

答案 0 :(得分:0)

为什么不使用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;
}