1

While composing an answer to When can I use a forward declaration?, I ran into an issue that I cannot explain.

// Forward declared class template:
template <typename T> struct X;

// Two other class templates that use it

template <typename T>
struct Foo {
   X<T>* m;
   Foo() : m(new X<T>) {}
};

template <typename T>
struct Bar {
   X<T> m;
};

// and a function that creates instances of Foo and Bar.

void test1()
{
   Foo<int> foo;
   Bar<int> bar;
}

// Define the class template after test1. On purpose.
template <typename T> struct X {};

int main()
{
}

When I compile the above program using g++ 4.9.3, I get compiler error for

Bar<int> bar;

but not for

Foo<int> foo;

Both require the definition of X since both fail to compile if omit the definition of X.

However, by just including the definition of X in the translation unit, Foo<int> foo; works while Bar<int> bar; does not work. Is this expected?

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270

0 Answers0