boost::associative_property_map() compile error

2020-05-07 05:22发布

问题:

using this link on boost website, I am able to compile the code here. and even get the answer (example). But when I do the same by defining in a class, I get the error as follows:

#include < as usual in the code >

class Test{

 std::map<std::string, std::string> name2address;
 boost::const_associative_property_map< std::map<std::string, std::string> >
                  address_map(name2address);


};

error is as follows:

error: ‘name2address’ is not a type

I have to use typedef and typename as follows to compile the code correctly. but I am still unable to use (insert, or the foo function (as provided in example)

please help, here is the code using typedefs

class Test{
  typedef typename std::map<std::string, std::string> name2address;
  boost::const_associative_property_map< std::map<std::string, std::string> >
                address_map(name2address);

 };

I have to pass this associative property map to another class, where I can use get and put functions as usual. How would i approach that ?

回答1:

This:

boost::const_associative_property_map< std::map<std::string, std::string> > address_map(name2address);

declares a variable and initialize it by calling the constructor with name2address. You cannot do it in a class declaration you have to do it in the class ctor :

class Test{

 std::map<std::string, std::string> name2address;
 boost::const_associative_property_map< std::map<std::string, std::string> >
                  address_map;
public:
 Test() : address_map(name2address) {}
};

This should solve the compilation issue, but I'm not sure it is the best possible layout depending on how you will use Test after that.