c++11 - C++ Compiler behavior with re-interpreting template parameter constants -
while working on raii-style guard object, ended encoding of guard state in template parameter. seems reasonable if, instance, want recursive / nested guard object that's aware of how many levels deep without space overhead (being pedantic, know) or eliminate runtime overheads. turned academic curiosity though...
something example:
template <unsigned depth> class guard { unsigned get_depth() const {return depth;} }; guard<2> g2; std::cout << reinterpret_cast< guard<5>* >( &g2 )->get_depth(); // works? crazy? useful?
i cannot life of me think of legitimate reason this, got me thinking if legal c++ , how compiler ought handle (if can @ all) or if it's silly through , through.
i assume because cast target needs known @ compile time, relevant template instantiated cast. has found useful, assuming work , has uses @ all, , if utilized?
the general question guess can reinterpret_cast
alter constant template parameters? if type hack (for want of better term) , g2
in case always return 2
(after casting)? or should return 5
(after casting)?
this undefined not because of strict aliasing rule. call get_depth
neither reads nor modifies value of object (a template non-type parameter isn't object), doesn't access (as defined in [defns.access]) within meaning of strict aliasing rule.
this controlled instead [class.mfct.non-static]/2:
if non-static member function of class
x
called object not of typex
, or of type derivedx
, behavior undefined.
Comments
Post a Comment