【发布时间】:2016-07-04 13:53:19
【问题描述】:
我有兴趣设计一个模板接口,其中函数的常量和返回类型本身会根据模板参数而变化。我已设法为返回类型执行此操作,如下所示。
template<typename T, bool canChange>
struct Changable{};
template<typename T>
struct Changable<T,true>
{
typedef T type;
};
template<typename T>
struct Changable<T,false>
{
typedef const T type;
};
template<typename T, bool canChange>
struct Data{
typedef typename Changable<T,canChange>::type DataType;
DataType m_data; //< This makes it const/non-const at compile time.
// This function will also make the return type const/non-const
// at compile time.
DataType& GetDataRef(){ return m_data;}
//However, it seems to me that I still need a second function
//with an explicit "const", which I can't seem to avoid.
DataType& GetDataRef()const{return m_data;}
};
我可以在编译时使用一些 SFINAE 魔法以某种方式避免在此处使用两个 const/non-const 函数吗? std::enable_if 在这里本来是理想的,但在我看来 const 不是一种类型,这种方法可能行不通。有什么建议吗?
【问题讨论】:
-
如果不需要重载,为什么不只保留
const版本? -
@KABoissonneault 我确实需要这两个版本,因为模板的常量会根据模板参数而改变。澄清一下,我确实希望能够创建某些
Data结构,这些结构可以在以后修改,而有些则保证不会改变。因此需要 const/non-const 功能。
标签: c++ templates c++11 sfinae