Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do I create an undordered map containing functions?

I have functions that are working with the following struct:

struct stm {
 size_t op; 
 std::string st_out; 
}

and I have declared the signature of the unordered map that will save the references:

std::unordered_map<uint64_t, std::function<int(stm&, const uint64_t)> instruction_actions;

I wrote the functions of which I want to save the reference:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

bool write(stm&s, const uint64_t item) {
  std::cout << "op: " << s.st_out << std::endl; 
  return true; 
}

but how should I add them in the map?

>Solution :

First things first, your function write is missing a return statement.


how should I add them in the map?

There are multiple ways of doing this as shown below:

std::unordered_map<uint64_t, std::function<int(stm&, const uint64_t)>> 
                  instruction_actions{{5, write}};

Or using std::map::insert

instruction_actions.insert({5, write});

Or using std::map::operator[]:

instruction_actions[5] = write;

Working demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading