Violation of template circular dependencies using template template parameters

If my understanding is correct, the following classic circular relationship between pattern classes:

template <class MyB>
struct A {
    MyB *b_;
};

template <class MyA>
struct B {
    MyA *a_;
};

If we want to create an instance Awith Band Bwith A, then we cannot start with any, since we would need to write: A<B<A<B<...>>>(infinite).

I think template template options provide a solution. The following code compiles (from gccversion 4.8.2):

template <class MyB>
struct A {
    MyB *b_;
};

template <template <class> class MyA>
struct B {
    MyA<B> *a_;
};

int main() {
    using MyB = B<A>;
    using MyA = A<MyB>;
    MyA a;
    MyB b;
    a.b_ = &b; b.a_ = &a;
    return 0;
}

Did I miss the essence of the problem?

The UPDATE . I just ran into this one that offers almost the exact same solution.

+4
source share
1 answer

, . , , :

  • , ,

    template <class MyB>
    struct A {
        MyB *b_;
    };
    
    template <template <class> class MyA>
    struct B {
        MyA<B> *a_;
    };
    
    int main() {
        using MyB = B<A>;
        using MyA = A<MyB>;
        MyA a;
        MyB b;
        a.b_ = &b; b.a_ = &a;
        return 0;
    }
    
  • , , struct/class

    template<class Common> struct A
    {
      typedef typename Common::BT B;
      B* b;
    };
    
    template<class Common> struct B
    {
      typedef typename Common::AT A;
      A* a;
    };
    
    struct Common {
      using AT = A<Common>;
      using BT = B<Common>;
    };
    
    
    int main() {
      A<Common> a;
      B<Common> b;
      return 0;
    }
    
  • , ,

    template <class MyA>
    struct B;
    
    template <typename ...MyB>
    struct A {
      B<A<>> *b_;
    };
    
    template <>
    struct A<> {};
    
    template <class MyA>
    struct B {
      A<B<MyA>> *a_;
    };
    
    int main() {
    
      using BoA = B<A<>>;
      using AoBoA = A<B<A<>>>;
    
      BoA obj1;
      AoBoA obj2;
    
      obj1.a_ = &obj2;
      obj2.b_ = &obj1;
    
      return 0;
    }
    

, , CRTP - , , ( ).

+2

Source: https://habr.com/ru/post/1618855/


All Articles