Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store methods as function pointers in a map container?

Tags:

I want to be able to call functions based on the data I read from file. So for each item type, I want to call the desired reader method. I wrote this code, but it does not compile where I want to add function pointers to the map. What is wrong?

#include <vector>
#include <map>
#include <iostream>
class reader
{

  std::map< std::string, void(*)()> functionCallMap; // function pointer
  void readA(){ std::cout << "reading A\n";};
  void readB(){ std::cout << "reading B\n";};;
public:
  reader()
  {
    *functionCallMap["A"] = &reader::readA;*
    *functionCallMap["B"] = &reader::readB;*
  }

  void read()
  {
   auto (*f) = functionCallMap["A"];
   (*f)();
  }



};

I am filling the map at Constructor.

like image 240
Ring Zero. Avatar asked Nov 16 '18 11:11

Ring Zero.


People also ask

How do you store function pointers?

Function pointers can be stored in variables, structs, unions, and arrays and passed to and from functions just like any other pointer type. They can also be called: a variable of type function pointer can be used in place of a function name.

Can a pointer store the address of a function?

A function pointer is a pointer variable, but it holds the address of a function, not the address of a data item. The only things you can do with a function pointer are read its value, assign its value, or call the function that it points toward.


1 Answers

You can use std::function with a lambda or std::bind :

class reader
{
    std::map<std::string, std::function<void()>> functionCallMap;

    void readA() { std::cout << "reading A\n"; };
    void readB() { std::cout << "reading B\n"; };

public:
    reader()
    {
        functionCallMap["A"] = [this]() { readA(); };
        functionCallMap["B"] = std::bind(&reader::readB, this);
    }

    void read()
    {
        functionCallMap["A"]();
        functionCallMap["B"]();
    }
};
like image 144
Siliace Avatar answered Oct 07 '22 14:10

Siliace