samedi 24 février 2018

Is std::is_convertible co-variant or contra-variant?

According to cppreference, std::is_convertible< From, To > should behave as if following imaginary function is well formed:

template < class To, class From >
To test() {
    return std::declval< From >();
}

This implies, that std::is_convertible< From, To >::value shall evaluate to true if To is covariant with From (in other words, when From is base class of To, std::is_convertible< From, To >::value should evaluate to true).

Let's say that we have two classes, struct Base {}; and struct Derived : public Base {};. Now, if we call imaginary test method, both test< Base*, Derived* >() and test< Derived*, Base* >() will actually be well formed, because you can return pointer to derived class even though formal return type is pointer to base class. But result of is_convertible< Base*, Derived* > and is_convertible< Derived*, Base* > will differ (std::is_convertible_v< Base*, Derived* > is equal to false. Is the description of this trait accurrate?

Aucun commentaire:

Enregistrer un commentaire