c++ Templates to change constness of a function -
i interested in designing template interface const ness of function , return type changes depending on template parameter. have managed return type follows.
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; //< makes const/non-const @ compile time. // function make return type const/non-const // @ compile time. datatype& getdataref(){ return m_data;} //however, seems me still need second function //with explicit "const", can't seem avoid. datatype& getdataref()const{return m_data;} };
can somehow avoid having 2 const/non-const functions here @ compile time using sfinae magic? std::enable_if have been ideal here seems me const not type , approach may not work. suggestions?
here example based on inheritance:
#include <type_traits> #include <iostream> template<typename t, bool canchange> struct changable { using type = const t; }; template<typename t> struct changable<t, true> { using type = std::decay_t<t>; }; template<typename, typename, bool> struct base; template<typename d, typename t> struct base<d, t, true> { using datatype = typename changable<t, true>::type; datatype& getdataref() { std::cout << "non-const" << std::endl; return static_cast<d*>(this)->m_data; } }; template<typename d, typename t> struct base<d, t, false> { using datatype = typename changable<t, false>::type; datatype& getdataref() const { std::cout << "const" << std::endl; return static_cast<const d*>(this)->m_data; } }; template<typename t, bool canchange> struct data: base<data<t, canchange>, t, canchange> { friend class base<data<t, canchange>, t, canchange>; typename base<data<t, canchange>, t, canchange>::datatype m_data{}; using base<data<t, canchange>, t, canchange>::getdataref; }; int main() { data<int, true> d1; data<int, false> d2; d1.getdataref(); d2.getdataref(); }
as requested, data
has 1 definition of getdataref
method.
1 available, const
1 or other one, depends on value of canchange
.
note friend
declaration. allows base class access private data members of data
.
Comments
Post a Comment