简体   繁体   中英

Storing function pointers in a std::map

I am trying to store function pointers in a map, along with a structure. The idea is to execute the corresponding functions, when I find specific values in the structure. The program is not compiling, and giving me lot of errors when I am trying to insert data into the map through std::make_pair. Here is the code that I have written. Please guide me as to what I am doing wrong here..

#include "stdafx.h"
#include <iostream>
#include <string>
#include <map>

struct _timeset
{
    int hr1;
    int min1;
    int secs1;
};

_timeset t1 = { 17, 10, 30 };

void fun1(void)
{
    std::cout << "inside fun1\n";
}

void fun2(void)
{
    std::cout << "inside fun2\n";
}

void fun3(void)
{
    std::cout << "inside fun3\n";
}

std::map<_timeset, void(*)()> m1;

int main()
{
    m1.insert(std::make_pair(t1, fun1));  //Compiling errors here



    return 0;
}

My basics in STL is very poor. I am using VS2013 Compiler. Also while iterating the map, can I execute the relevant function with something like :

std::map<_timeset, void(*)()>::iterator it1;
    int i = 0;
    for (i=0,it1 = m1.begin(); it1 != m1.end(); it1++,i++)
    {

        _timeset _t = it1->first;
         //Check Values in _t, and then execute the corresponding function in the map

            (*it1->second)();
    }

many thanks,

You need to specify comparator for _timeset for std::map to work, for example:

struct _timeset
{
    int hr1;
    int min1;
    int secs1;
    bool operator<( const _timeset &t ) const {
        return std::make_tuple( hr1, min1, secs1 ) < std::make_tuple( t.hr1, t.min1, t.secs1 );
    }
};

or you can make it as lamba as described here

Also while iterating the map, can I execute the relevant function with something like

yes you can, also you do not have to copy your struct _timeset :

int i = 0;
for ( it1 = m1.begin(); it1 != m1.end(); it1++,i++)
{

    const _timeset &_t = it1->first;
     //Check Values in _t, and then execute the corresponding function in the map

        (*it1->second)();
}

if you want to store functions with different signature, use std::function :

typedef std::function<void()> func;
std::map<_timeset, func> m1;

void fun1();
void func2( int );
struct foobar { void func3(); };

m1.insert( std::make_pair( t, func1 ) ); // signature matches, no need for bind
m1.insert( std::make_pair( t, std::bind( func2, 123 ) ) ); // signature does not match func2(123) will be called
foobar *pf = ...;
m1.insert( std::make_pair( t, std::bind( func3, pf ) ) ); // signature does not match, pf->func3() will be called
// etc

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