我曾经认为'typedef'不会自动继承.但下面的代码表示不同的东西.
#include <iostream>
#include <type_traits>
struct A
{
typedef int X;
};
struct A_
{
typedef char X;
};
struct B : A {};
struct B_ : A, A_ {};
template< typename ... Ts >
using void_t = void;
template< typename T, typename = void >
struct has_typedef_X : std::false_type {};
template< typename T >
struct has_typedef_X< T, void_t<typename T::X> > : std::true_type {};
int main()
{
std::cout << std::boolalpha;
std::cout << has_typedef_X<A>::value << std::endl;
std::cout << has_typedef_X<A_>::value << std::endl; …Run Code Online (Sandbox Code Playgroud) 为什么这有效:
template <typename T>
struct foo
{
};
struct A
{
typedef foo<A> type;
};
struct B : public A
{
typedef foo<B> type;
};
int main()
{
B::type john;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但不是这个:
template <typename T>
struct foo
{
};
template <typename T>
struct Shared
{
typedef foo<T> type;
};
struct A : public Shared<A>
{
};
struct B : public A, public Shared<B>
{
};
int main()
{
// g++ 4.5 says :
// error: reference to 'type' …Run Code Online (Sandbox Code Playgroud)