c++ - Cast for upcasting only -


we know c-style casts considered evil in c++. why replaced const_cast<>, static_cast<>, , dynamic_cast<> provide more bespoke casting, allowing programmer allow intended classes of conversions. far, good.

however, there seems no builtin syntax perform explicit upcast: means perform otherwise implicit conversion in base& baseref = derived explicitly without allowing reverse.

while know quite small corner case (most of time implicit conversions work fine), wondering techniques available implement such cast in user code. thinking along lines of

template<class t> class upcast {     public:         template<class u, typename = typename std::enable_if<std::is_convertible<u, t>::value>::type>         upcast(u value) : value(value) {}         operator t() { return value; }     private:         t value; }; 

however, seems complicated good, , since i'm not expert in template-metaprogramming, ask whether there different/better/simpler approaches.

std::forward<t&> allow upcasts:

struct {}; struct b : {}; a; b b; auto& x = std::forward<a&>(b); // ok auto& y = std::forward<b&>(a); // fails auto* px = std::forward<a*>(&b); // ok auto* py = std::forward<b*>(&a); // fails 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -