Rinat Veliakhmedov
Rinat Veliakhmedov

Reputation: 1039

Is there a way to resolve this template circular dependency

Is there a general approach to solve this type of circular dependencies in template or is it impossible to make work?

#include <tuple>

template<class... T>
struct A {
    std::tuple<T...> t;
};

template<class type_of_A>
struct D1 {
    type_of_A* p;
};
template<class type_of_A>
struct D2 {
    type_of_A* p;
};

using A_type = A<D1<???>, D2<???>>;  // <------

int main() { }

Upvotes: 0

Views: 89

Answers (1)

Quentin
Quentin

Reputation: 63114

As usual, insert a named indirection into the mix to break the infinite recursion:

template<class... T>
struct A {
    std::tuple<T...> t;
};

template<class type_of_A>
struct D1 {
    typename type_of_A::type* p; // Indirection
};

template<class type_of_A>
struct D2 {
    typename type_of_A::type* p; // Indirection
};

// Type factory while we're at it
template <template <class> class... Ds>
struct MakeA {
    using type = A<Ds<MakeA>...>; // Hey, that's me!
};

using A_type = typename MakeA<D1, D2>::type;

The behaviour of MakeAs injected-class-name is a bonus, but we could spell it out as MakeA<Ds...>.

See it live on Coliru

Upvotes: 4

Related Questions