circular dependency with class templates

I am trying to create a bidirectional association between class templates, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

#include <iostream>

using namespace std;


template <typename T>
struct AT
{
    T* p;
...
};

template <typename T>
struct BT
{
    T* p;
...
};

int main() {

    using B = BT<A>;
    using A = AT<B>;

    AT<B> a;
    BT<A> b;

    return 0;
}


This code fails to compile with the following error with gcc:
source>:21:18: error: 'A' was not declared in this scope; did you mean 'AT'?
21 | using B = BT<A>;

I am not sure how I should declare a template based on the other one. Is there a solution to this compilation error or a better solution to my bidirectional association desing?

Thanks

1
2
using B = BT<A>;
using A = ...

You're trying to use an identifier before it's declared.
But more to the point... the object doesn't make sense.

So, let's see: What is a 'B' object? Well, it's an BT<A>. Okay, what's an 'A' object: It's a AT<B>.
So a B is a BT<AT<B>>? It makes no sense.

At some point, T needs to be instantiated as some sort of concrete type that doesn't depend on another type.
You could have something like:
1
2
    AT<BT<int>> a;
    BT<AT<int>> b;

But it's hard to tell what you want.
Last edited on
It seems that you are trying to create:

1
2
struct AT { BT<AT<BT<AT<...>>>>* p; };
struct BT { AT<BT<AT<BT<...>>>>* p; };

What exactly are you trying to represent?
I see your point. What I am trying to do doesn't make much sense.

I am trying to model a bidirectional association between two objects: A contains a pointer to B and, viceversa, B contains a pointer to A. If I did that without templates, it would be absolutely fine. The reason I am doing it with templates, it's because I want to replace each component individually with a mock object using GMock framework as described here: https://chromium.googlesource.com/external/github.com/google/googletest/+/HEAD/googlemock/docs/cook_book.md#mockingnonvirtualmethods.
Topic archived. No new replies allowed.