c++ - Initializing std::map with an array of std::pairs issue (pointer error?) -
i trying understand how initialize private const std::map
properly. have studied this well-known topic none of answers suitable me, because forced use old gcc , boost versions (gcc 4.4, boost 1.41 -> c++11 features limited, boost::asign::map_list_of not compile) and, moreover, don't want use class member function std::map initialization due need of doing outside class @ time of object construction.
however, there overloaded constructor std::map
accepts 2 iterators (this thread inspired me too), , workaround:
template <typename arg, typename callback> class callbackselector { private: const std::map<arg, callback> mapping; public: callbackselector(std::pair<arg, callback> _mapping[]): mapping(_mapping, _mapping + sizeof(_mapping)/sizeof(std::pair<arg, callback>)) { //boost_assert(sizeof _mapping)/(sizeof (std::pair<arg, callback>)) == 2); std::cout << "sizeof _mapping " << sizeof _mapping << std::endl; std::cout << "sizeof (std::pair<arg, callback>) " << sizeof (std::pair<std::string, boost::function<void(void)> >) << std::endl; }; }; void pamevent() {} void defaultevent() {} int main(int argc, char** argv) { std::pair<std::string, boost::function<void(void)> > _mapping[] = { std::make_pair("pam:", boost::bind(&pamevent)), std::make_pair("none", boost::bind(&defaultevent)) }; std::cout << "sizeof _mapping " << sizeof _mapping << std::endl; std::cout << "sizeof (std::pair<arg, callback>) " << sizeof (std::pair<std::string, boost::function<void(void)> >) << std::endl; callbackselector<std::string, boost::function<void(void)> > selector(_mapping); }
(the full executable version of example)
if uncomment line boost_assert macro, code not compiled, because size of mapping unequal 2 due error of passing std::pair<std::string, boost::function<void(void)> > _mapping[]
callbackselector class constructor. can verify looking @ output:
sizeof _mapping 80 //in int main() sizeof (std::pair<arg, callback>) 40 sizeof _mapping 8 //in callbackselector constructor sizeof (std::pair<arg, callback>) 40 //the array size has decreased tenfold
i'll glad if find (apparently?) simple mistake. thank you.
there's no way determine size of array given pointer it. either pass size separate argument:
callbackselector(std::pair<arg, callback> mapping[], size_t size) : mapping(mapping, mapping + size)
or infer template parameter:
template <size_t size> callbackselector(std::pair<arg, callback> (&mapping)[size]) : mapping(mapping, mapping + size)
or, in c++11 or later, take initializer_list
argument
callbackselector(std::initializer_list<std::pair<arg, callback>> mapping) : mapping(mapping.begin(), mapping.end()) // usage example callbackselector<std::string, boost::function<void(void)> > selector { {arg1, callback1}, {arg2, callback2} };
(note: took liberty of renaming _mapping
, reserved name shouldn't have been using).
Comments
Post a Comment