Broadcast only

We all know that C-style is discarded in C ++ as evil. That is why they are replaced with const_cast<>, static_cast<>and dynamic_cast<>, to provide a more personalized casting, allowing the programmer to allow only the alleged transformation classes. So far so good.

However, there seems to be no built-in syntax for performing an explicit upcast: A means performing an explicitly implicit conversion to Base& baseRef = derivedexplicitly, avoiding the opposite.

Although I know this is a rather small angular case (in most cases, implicit conversions work very well), I was wondering what methods are available for implementing this kind in user code. I was thinking about something in the ranks

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;
};

, , , , // .

+4
1

std::forward<T&> upcasts:

struct A {};
struct B : A {};
A 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
+2

Source: https://habr.com/ru/post/1650552/


All Articles