简体   繁体   中英

Using function pointers in std::map

I'm a newbie to C++ and having an issue regarding std:map with function pointers.

I have created a map which has a string as the key and stored a function pointer as the value. I faced a complication when I tried to use insert() function to add a function pointer. However, it worked when I used [] operator. If you can, please explain this difference.

Here is a sample code I wrote.

OperatorFactory.h

#ifndef OPERATORFACTORY_H
#define OPERATORFACTORY_H

#include <string>
#include <map>

using namespace std;

class OperatorFactory
{
    public:
        static bool AddOperator(string sOperator, void* (*fSolvingFunction)(void*));
        static bool RemoveOperator(string sOperator);
        static void RemoveAllOperators();

    private:
        static map<string , void* (*) (void*)> map_OperatorMap;
};

// Static member re-declaration
map<string, void* (*) (void*)>  OperatorFactory::map_OperatorMap;

#endif // OPERATORFACTORY_H

OperatorFactory.cpp

#include "OperatorFactory.h"

void OperatorFactory::RemoveAllOperators()
{
    map_OperatorMap.clear();
}

bool OperatorFactory::RemoveOperator(string sOperator)
{
    return map_OperatorMap.erase(sOperator) != 0;
}

bool OperatorFactory::AddOperator(string sOperator, void* (*fSolvingFunction)(void*))
{
    // This line works well.
    map_OperatorMap[sOperator] = fSolvingFunction;

    // But this line doesn't.
    // map_OperatorMap.insert(sOperator, fSolvingFunction); // Error
    return true;

}

The Error says :

error: no matching function for call to 'std::map<std::basic_string<char>, void* (*)(void*)>::insert(std::string&, void* (*&)(void*))'

Even though I got this working (compiled) with the [] operator, I would like to know why I got an error when using insert() .

Thank you.

You insert elements into std::map using a std::pair of the key and value:

map.insert(std::make_pair(key,value));

Alternatively you can emplace values in c++11:

map.emplace(key,value);

The [] operator returns a reference to the value for the key passed in:

value_type & 

And automatically constructs an element for that key if it doesn't already exist. Make sure you understand what the difference in behavior is between insert() and the [] operator before using them (the latter will replace existing values for a key for example).

See http://en.cppreference.com/w/cpp/container/map for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM