C++ 使用boost::fusion::map的常量正确性问题
我正在编写一些使用boost::fusion::map的类。下面是一个简化的代码:C++ 使用boost::fusion::map的常量正确性问题,c++,const-correctness,boost-fusion,C++,Const Correctness,Boost Fusion,我正在编写一些使用boost::fusion::map的类。下面是一个简化的代码: 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
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);
}
};
模板
结构对象
{
类型定义
字体名
boost::fusion::result\u of::as\u map::type map\u type;
地图类型地图;
对象()
:map()
{}
对象(对象常量和其他)
:map(其他.map)
{}
对象和运算符=(对象常量和其他)
{
map=other.map;
归还*这个;
}
//非常量版本
模板
字体名
boost::fusion::result\u of::at\u key::type get()
{
返回boost::fusion::at_键(map);
}
//常量版本
模板
字体名
boost::fusion::result\u of::at\u key::type get()const
{
返回boost::fusion::at_键(map);
}
};
另一类:
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>();
}
};
模板
类字段
{
私人:
Obj&Obj_m;
公众:
//由\c运算符()返回的类型
类型定义
字体名
boost::fusion::result\u of::at\u key::type return\u type;
//由\c运算符()常量返回的类型
类型定义
字体名
boost::fusion::result\u of::at\u key::type return\u type\u const;
字段(Obj和Obj)
:obj_m(obj)
{ }
虚拟场()
{ }
返回类型运算符()
{
返回obj_m.template get();
}
返回类型常量运算符()()常量
{
/*
*问题!
*/
对象常量&对象常量=对象常量;
返回obj_const.template get();
}
};
在上面代码的注释中查找“PROBLEM!”。在该方法中,编译器忽略该方法的常量限定符,并调用obj_m.get()的非常量版本,以执行以下操作:
obj_m.template get<FieldId>() = 10;
obj_m.template get()=10;
这是不正确的,因为此方法是常量!然后,为了强制编译器调用const版本,声明对obj_m的const引用。现在是句子
obj_const.template get<FieldId>() = 0;
obj_const.template get()=0;
产生编译错误。到目前为止,对于当前的方法来说,这不是一个问题,但是对于常量的正确性来说并不方便,而且肯定是不需要的
知道为什么会这样吗?
谢谢