[Bug c++/20011] New: Templates and cyclic dependencies

jmoro at latentzero dot com gcc-bugzilla@gcc.gnu.org
Wed Feb 16 20:38:00 GMT 2005


Hello, the new support of two-stage name-lookup for templates in gcc 3.4.0 for
C++ brings a problem that
I don't know how to resolve.
I would like to know what is your recommended way of dealing with the following.


Here is some code that used to compile and link on gcc 3.3 (sorry to copy some
code but that's key to understanding the problem)

///////
// A.h
///////
class B;

class A
{
public: 
 
  A(){}
  ~A(){}

  template <class T> int f( T t )
  {
    B b;
    return ( b.getInt() + t );
  }

  int getInt() const
  {
    return 1;
  }
};


//////
//B.h
//////
class A;

class B
{
public:

  B(){}
  ~B(){}

  template <class T> int g( T t )
  {
    A a;
    return ( a.getInt() + t );
  }

  int getInt() const
  {
    return 2;
  }
};


///////////
//Main.cpp
///////////
#include "A.h"
#include "B.h"

int main( void )
{
  A a;
  int i = 1;
  a.f( i );

  B b;
  b.g( i );
}


As you can see in A.h, the template method f() uses B and in B.h, the template
method g() uses A.
As these methods were only compiled at instantiation time (with gcc 3.3) the
fact that A uses B and B uses A was not a problem but if I compile the same code
with gcc 3.4

I have:

> gcc -v
Reading specs from /var/gnu/3.4.0/lib/gcc/sparc-sun-solaris2.8/3.4.0/specs
Configured with: ../gcc-3.4.0/configure --prefix=/var/gnu/3.4.0 --disable-nls
--enable-languages=c,c++
Thread model: posix
gcc version 3.4.0


>  gcc -c -save-temps Main.cpp
In file included from Main.cpp:1:
A.h: In member function `int A::f(T)':
A.h:13: error: invalid use of undefined type `struct B'
A.h:1: error: forward declaration of `struct B'

This is normal as with 3.4, B needs to be known at definition time in A.h as it
is not dependent on a template parameter.
But obvioulsy, if I change my code so that A.h includes B.h, and B.h includes
B.h, I have a cyclic dependency and it won't compile.

The next step in order to remove such a dependency is usually to get the method
code out of the header file and put it in the cpp file. But of course, this is a
template method and the only method I know to do this with templates is to use
the keyword export... that you don't support.

This last point is fair enough as lots of compilers don't support it but I would
like to know what is you recommended solution to fix this problem?

-- 
           Summary: Templates and cyclic dependencies
           Product: gcc
           Version: 3.4.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P1
         Component: c++
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: jmoro at latentzero dot com
                CC: gcc-bugs at gcc dot gnu dot org


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=20011



More information about the Gcc-bugs mailing list