1

I'm writing some classes that use boost::fusion::map. Bellow you find a simplified code:

template <typename ObjDef>
struct Object
{
typedef 
typename 
boost::fusion::result_of::as_map<valid_list_of_fusion_pairs>::type map_type;

map_type map;

Object()
: map()
{}

Object(Object const & other)
: map(other.map)
{}

Object & operator=(Object const & other)
{
  map = other.map;
  return *this;
}

// non-const version
template <typename FieldId>
typename 
boost::fusion::result_of::at_key<map_type, FieldId>::type  get()
{
return boost::fusion::at_key<FieldId>(map);
}

// const version
template <typename FieldId>
typename 
boost::fusion::result_of::at_key<map_type const, FieldId>::type get() const
{
return boost::fusion::at_key<FieldId>(map);
}

};

and another class:

template <typename Obj, typename FieldId>
class Field
{
private:
  Obj &obj_m;

public:

// type returned by \c operator()
typedef
typename 
boost::fusion::result_of::at_key<typename Obj::map_type, FieldId>::type return_type;

// type returned by \c operator() const
typedef
typename 
boost::fusion::result_of::at_key<typename Obj::map_type const, FieldId>::type return_type_const;

Field(Obj &obj)
: obj_m(obj)
{ }

virtual ~Field()
{ }

return_type operator()()
{
  return obj_m.template get<FieldId>();
}

return_type_const operator()() const
{
  /*
  * PROBLEM!
  */
  Obj const & obj_const = obj_m;
  return obj_const.template get<FieldId>();
}
};

Look for "PROBLEM!" in the comments in the above code. In that method, the compiler ignores the const qualifier of the method and calls the non-const version of obj_m.get() allowing to do something like:

obj_m.template get<FieldId>() = 10;

which is not correct since this method is const! Then, to force the compiler to call the const version, a const reference to obj_m is declared. Now the sentence

obj_const.template get<FieldId>() = 0;

produces a compilation error. So far this is not a problem for the current method,but it is not convenient for const correctness and it is definitively undesired

any idea why is this happening? thanks!

4

0 回答 0