#include "boost/multi_index_container.hpp" #include "boost/multi_index/member.hpp" #include "boost/multi_index/ordered_index.hpp" #include #include #include #include using namespace boost::multi_index; struct employee { int id; std:: string name; employee(int id, std::string const& name): id{id}, name{name}{} }; bool operator<(employee const& lhs, employee const& rhs) { return lhs.id < rhs.id; } std::ostream& operator<<(std::ostream& os, employee const& e) { os << e.name << " [" << e.id << "]"; return os; } struct id; struct name; // define a multiply indexed set with indices by id and name using employees = boost::multi_index_container< employee, indexed_by< // sort by operator<(employee, employee) ordered_unique, identity>, // sort by less on name ordered_non_unique, member>>>; void print_out_by_name(employees const& es) { // get a view to index #1 (name) auto & name_index(es.get()); // use name_index as a regular std::set std::copy( name_index.begin(),name_index.end(), std::ostream_iterator(std::cout, "\n")); } int main() { employees es; es.insert({0, "Adam"}); es.insert({1, "Eve"}); es.insert({2, "Bob"}); std::cout << "Employee ids must be unique.\n"; std::cout << "Here are the original records:\n"; print_out_by_name(es); std::cout << "Changing Bob's id to one which is already taken (1).\n"; std::cout << "Calling modify() with a callable that violates the index constraint\n"; std::cout << "and a rollback callable that does nothing to fix the problem.\n"; auto& name_index(es.get()); auto it(name_index.find("Bob")); bool succeed{name_index.modify( it, [](employee& e) {e.id = 1;}, [](employee& e) { std::cout << "[confirming rollback called]\n";})}; std::cout << "Call succeeded: " << std::boolalpha << succeed << "\n"; std::cout << "Here are the post-modify-call records.\n"; print_out_by_name(es); std::cout << "We now have a duplicated unique key value.\n"; std::cout << "\nIf the rollback fails to correct the problem, should the record not be deleted?\n"; }