C
Nash26 schrieb:
camper schrieb:
Wozu braucht man so etwas?
struct foo : Derived, Base {};
und dann schauen, ob ein (eindeutiges) foo::MyType existiert.
Ich verstehe nicht was du meinst. In dem Fall hat foo auch wieder ein MyType.
Keineswegs, schließlich wäre die Auflösung mehrdeutig.
#include <type_traits>
#include <utility>
struct Base { typedef int MyType; };
struct Derived : Base { };
struct Derived2 : Base { using Base::MyType; };
struct Derived3 : Base { typedef char MyType; };
struct Derived4 : Base { typedef int MyType; };
struct foo : Derived, Base {};
struct bar : Derived2, Base {};
struct baz : Derived3, Base {};
struct boo : Derived4, Base {};
template <typename T> struct identity { typedef T type; };
template <typename T, typename = typename T::MyType>
std::true_type has_MyType(identity<T>);
std::false_type has_MyType(...);
int main()
{
static_assert( decltype(has_MyType(identity<Base>()))::value, "Base should have MyType" );
static_assert( decltype(has_MyType(identity<Derived>()))::value, "Derived should have MyType" );
static_assert( decltype(has_MyType(identity<Derived2>()))::value, "Derived2 should have MyType" );
static_assert( decltype(has_MyType(identity<Derived3>()))::value, "Derived3 should have MyType" );
static_assert( decltype(has_MyType(identity<foo>()))::value, "should have inherited MyType" );
static_assert( decltype(has_MyType(identity<bar>()))::value, "should have inherited MyType" );
static_assert( !decltype(has_MyType(identity<baz>()))::value, "should be ambigous" );
static_assert( !decltype(has_MyType(identity<boo>()))::value, "should be ambigous" );
}