Home > OS >  how do I create an undordered map containing functions?
how do I create an undordered map containing functions?

Time:11-22

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:

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?

CodePudding user response:

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

  • Related