-1

I have one library that declared a template function:

template <typename T>
void Foo(blah...)
{
   class Bar mybar;
   ...
}

class Bar is not defined in this library, but since it's just a template it should not be instantiated at this time; so by explicitly using the class keyword, the library is successfully compiled.

Later in the main program file where I do need to instantiate this template, I included the file with the complete definition of class Bar. It used to work with gcc 4.4.2 but now upgraded to 4.8.1 I am getting the error:

"Foo(blah...) [with T = blahblah]::Bar mybar has incomplete type"

It seems like the compiler treated Bar as a temporary class declaration inside the template function instead of a forwarded class. I'm wondering if there is anything to work around this or this trick is not supposed to work anyhow? The point to do this is, class Bar has a lot of dependencies and most program using my library does not need class Bar, so no point to link all the extra libs that class Bar depends on.

TIA

R Sahu
  • 196,807
  • 13
  • 136
  • 247
Shine
  • 1
  • 1

1 Answers1

1

The line

class Bar mybar;

declares Bar to be a nested class of the function template and defines mybar as a member variable of type the nested class Bar. It does not declare mybar to be an instance of a class Bar that might exist outside the function template.

If you want mybar to be an instance of the Bar that is defined outside the function template, you need to use:

class Bar;

template <typename T>
void Foo(blah...)
{
   Bar mybar;
   ...
}

Update

The following program compiles and builds fine with g++ -Wall -std=c++11

class Bar;

template <typename T>
void Foo()
{
   Bar mybar;
}

class Bar
{
   public:
      Bar() {}
};

int main()
{
   Foo<int>();
   Foo<double>();
}
R Sahu
  • 196,807
  • 13
  • 136
  • 247
  • already tried. It wont even let me compile the library: "invalid use of incomplete type 'class Bar'" – Shine Mar 02 '15 at 05:58
  • I'm pretty sure this works, but my problem is that I need to compile the lib without the definition of class Bar (ie, only the upper part of your sample), It will be defined later but before instantiation. But thanks a lot for your time! I think I better give this up and come up with a new solution. :-) – Shine Mar 02 '15 at 06:11
  • @Shine, which lib are you talking about? The upper part of the code is syntactically correct. You will need `Bar` only when you instantiate the function template. – R Sahu Mar 02 '15 at 06:18