Namespaces
Variants

Talk:cpp/types/is base of

From cppreference.com

Possible implementation (I don't know what this site's policy would be on reviewing it before putting it into the main page):

#include <type_traits> #include <utility> namespace details { template <typename Base> std::true_type is_base_of_test_func(Base*); template <typename Base> std::false_type is_base_of_test_func(void*); template <typename Base, typename Derived> using pre_is_base_of = decltype(is_base_of_test_func<Base>(std::declval<Derived*>())); // with <experimental/type_traits>: // template <typename Base, typename Derived> // using pre_is_base_of2 = std::experimental::detected_or_t<std::true_type, pre_is_base_of, Base, Derived>; template <typename Base, typename Derived, typename = void> struct pre_is_base_of2 : public std::true_type { }; // note std::void_t is a C++17 feature template <typename Base, typename Derived> struct pre_is_base_of2<Base, Derived, std::void_t<pre_is_base_of<Base, Derived>>> : public pre_is_base_of<Base, Derived> { }; }; template <typename Base, typename Derived, bool = std::is_class<Base>::value && std::is_class<Derived>::value> struct is_base_of : public std::false_type { }; template <typename Base, typename Derived> struct is_base_of<Base, Derived, true> : public details::pre_is_base_of2<Base, Derived> { };

Outline: details::pre_is_base_of does most of the work; but if Base is a private base of Derived, then it gives an access error because overload resolution happens entirely before access checking. So, details::pre_is_base_of2 filters out those errors and changes them to a std::true_type result. Then, the main is_base_of checks that the arguments satisfy std::is_class before delegating to details::pre_is_base_of2.

173.196.147.98 14:44, 18 August 2016 (PDT)