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? ]
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With