mar*_*ark 4 c++ templates type-traits template-meta-programming c++11
我目前正在编写一个接口类,它应该提供对复杂结构的内部元素的访问,作为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
};
Run Code Online (Sandbox Code Playgroud)
注意:分离/创建2个版本的接口的根本原因是它们将提供对不同实例的访问config
- 一个是可写的,另一个是不可写的.正在开发的子系统是嵌入式Netconf代理,它支持<running>
和<candidate>
配置.
小智 5
这似乎是最简单的专业化:
template< bool isConst >
struct Interface;
template <>
struct Interface<false>
{
TypeA& GetXpo3Container()
{
return config_.type_a_member_;
}
};
template <>
struct Interface<true>
{
const TypeA& GetXpo3Container() const
{
return config_.type_a_member_;
}
};
Run Code Online (Sandbox Code Playgroud)
编辑:虽然我不完全确定这会增加什么.拥有它会不会更容易
struct Interface
{
TypeA::type& GetXpo3Container()
{
return config_.type_a_member_;
}
const TypeA::type& GetXpo3Container() const
{
return config_.type_a_member_;
}
};
Run Code Online (Sandbox Code Playgroud)
并const Interface
在适当的地方使用?或者这不是其他原因的选择吗?
编辑2:我的std::enable_if
使用是错误的,它现在已经消失了.
归档时间: |
|
查看次数: |
916 次 |
最近记录: |