MSVC 2008 はこのコードをコンパイルしません:
template <class Derived>
struct B
{
typename Derived::type t;
};
struct D : B<D>
{
typedef int type;
};
void main()
{
D d;
}
表示されるエラーは、「エラー C2039: 'type' : is not a member of 'D'」です。何か案は?
B は、それ自体を定義するために D の完全な型定義を必要とするためです。
おそらく期待していることは、次のようになります。
template <class Derived>
struct B
{
B() {
typename Derived::type t;
}
};
struct D : B<D>
{
typedef int type;
};
void main()
{
D d;
}
これが機能するのは、D() (したがって B()) のインスタンス化の時点で、コンパイラが型の完全な定義を持っているためです。
g++ は、より役立つエラー メッセージを表示します。
g++ -c -o /tmp/to /tmp/t.cpp
/tmp/t.cpp: 'B' のインスタンス化:
/tmp/t.cpp:8: ここからインスタンス化
/tmp/t.cpp:4:エラー: 不完全な型 'struct D' の無効な使用<br> /tmp/t.cpp:7: エラー: 'struct D' の前方宣言<br> /tmp/t.cpp:12: エラー: '::main ' 'int' を返さなければなりません