c++ - Is it possible to distinguish a `const` variable from a non-`const` one and from a `const&` reference? -
suppose wanted make own reference ("smart pointer") type guaranteed refer immutable data, rather merely immutably-viewed data. in other words, data can't mutated anyone, opposed not through particular reference. not easy, because c++ considers const
things subcase of mutable-access things, , &
references implicitly convert const &
, likewise *
const *
.
let's call type:
template<typename t> class immref { ... };
one straightforward thing can declare:
template<typename t> struct imm { const t value; };
and allow creating immref
s out of imm
s, or other immref
s. here variable declared const
, it's not possible make mutable references it, , in fact immutable. (unless internally uses mutable
, since there's nothing can that, let's ignore it.)
that works, greater flexibility, wider applicability, , compatibility other code doesn't know our imm
type, better if create immref
s any const
-declared variable. it's not clear whether c++ makes possible distinguish "a variable declared const
" "a const
reference variable", or "a variable not declared const
".
in other words, should work:
const int myconstnumber = 666; immref<int> myimmref = immref(myconstnumber);
but should not:
int mynumber = 666; immref<int> myimmref = immref(mynumber);
and should not:
const int& myconstref = mynumber; immref<int> myimmref = immref(myconstref);
is there dark template magic lets me this?
there's no way tell reference refers real const
object. , there's no way function tell whether argument names object or reference.
decltype
tell name belongs const
object (not reference), name must in scope. usage can't encapsulated in template.
a macro job, if really want it:
#define make_immref( name ) immref< decltype( name ) >{ name } template<typename t> struct immref { static_assert ( std::is_const< t >::value, "immref requires constant." ); t & ref; };
Comments
Post a Comment