Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect whether a type is a visible base of another type?

If I do

struct A{};
struct C:private A{};

typedef char (&yes)[1];
typedef char (&no)[2];

template <typename B, typename D>
struct Host
{
 operator B*() const;
 operator D*();
};

template <typename B, typename D>
struct is_base_of
{
template <typename T> 
static yes check(D*, T);
static no check(B*, int);

static const bool value = sizeof(check(Host<B,D>(), int())) == sizeof(yes);
};

int main(){
 std::cout<<is_base_of<A,C>::value<<std::endl;
}

I get a 1. I would like to get a 0 when C is a private A, and a 1 when C is a public A.

[the code is derived from How does `is_base_of` work? ]

like image 990
Fabio Dalla Libera Avatar asked Mar 27 '12 18:03

Fabio Dalla Libera


1 Answers

Do you have access to a compiler with C++11 support?

If so, you can combine Chad's use of static_cast with decltype to create a very simple type trait implementation (as demonstrated in this question). As per Jonathan Wakely's suggestion, the references have been replaced with pointers to avoid false positives when D defines an operator B&().

template<typename> struct AnyReturn { typedef void type; };

template<typename B, typename D, typename Sfinae = void>
struct is_base_of: std::false_type {};

template<typename B, typename D>
struct is_base_of<B, D,
    typename AnyReturn< decltype( static_cast<B*>( std::declval<D*>() ) ) >::type
>: std::true_type {};

When using gcc 4.7:

struct Base {};
struct PublicDerived  : public  Base {};
struct PrivateDerived : private Base {};

int main()
{
    std::cout << is_base_of<Base, PublicDerived >::value << std::endl; // prints 1
    std::cout << is_base_of<Base, PrivateDerived>::value << std::endl; // prints 0
    return 0;
}
like image 110
Michael Pierce Avatar answered Oct 30 '22 18:10

Michael Pierce