【发布时间】:2012-04-11 16:30:48
【问题描述】:
我目前正在编写一个接口类,它应该提供对复杂结构的内部元素的访问,作为 const 或非 const 引用。这个想法是一些模块被授予 const 访问权限,而一些模块被授予完全访问权限。
我已经使用 'type_traits' 'std::add_const' 有条件地限定内部成员函数的返回类型,不幸的是我想不出有条件地将成员函数限定为 const 或非 const 的方法。
这甚至可能吗?如果是这样怎么办?
例如:
template< typename T, bool isConst >
struct apply_const
{
typedef T type;
};
template<typename T>
struct apply_const<T, true>
{
typedef typename std::add_const<T>::type type;
};
template< bool isConst >
const Interface
{
/// @brief get the TypeA member
typename apply_const<TypeA, isConst >::type& GetXpo3Container() // how do I conditionally add a const qualifier
{
return config_.type_a_member_;
}
typename apply_const<Profile, isConst >::type& GetProfile( unint32_t id ) // qualifier ???
{
return config_.profiles.get( id );
}
// .... lots more access functions
ConfigType config_; // the config
};
注意:分离/创建两个版本的接口的根本原因是它们将提供对config 不同实例的访问——一个是可写的,一个是不可写的。正在开发的子系统是一个嵌入式Netconf Agent,支持<running>和<candidate>配置。
【问题讨论】:
-
使用两个重载(一个 const 和一个非常量),并使用 SFINAE 一次只启用其中一个。
-
2 个重载实际上并没有保存任何东西(如下所述)。目标是提供 2 个版本的“接口”,一种是所有成员函数都返回“const”引用,另一种是所有成员函数都返回非 const 引用。返回类型的常量性不仅仅是成员函数的限定问题。我想我只需要对成员函数没有限制就可以了,这不是太大的问题。
标签: c++ templates c++11 template-meta-programming typetraits