1

I have the following struct:

template <typename T>
struct A
{
    T t;
};

In the other struct I would like to define a pointer to the struct A:

struct B
{
    //A* a;
};

A specific type for object of type A will be known during object A creation. How to define a pointer to the template type inside struct B ?

Lundin
  • 195,001
  • 40
  • 254
  • 396
Irbis
  • 1,432
  • 1
  • 13
  • 39
  • Either `B` also needs to be a template with the same type `T` or you need type erasure. Does this answer your question? https://stackoverflow.com/questions/34815513/what-is-type-erasure-in-c – Homer512 Jun 16 '23 at 08:30
  • `A* a` / `template struct B { A* a; };` – 0RR Jun 16 '23 at 08:47
  • I don't want use template for struct B so the type erasure is the only way to solve the above issue. – Irbis Jun 16 '23 at 08:53
  • @Irbis I think this is an [XY problem](https://xyproblem.info/). What problem are you really trying to solve? – Ted Lyngmo Jun 16 '23 at 08:56
  • `struct B { void* a; };` pointer other than a void pointer can be assigned pointers pointers to arbitary structs and template instantiations are entirely unrelated in this regard... – fabian Jun 16 '23 at 16:57

1 Answers1

6

How to define a pointer to the template type?

A class template is not a type so you can't have pointers to them. You need to instantiate the class template in order to get a class based on the template and then you can make pointers to instances of that class.

Example:

template<class T>
struct B
{
    A<T>* a;
};

Here B<int> would hold a pointer to A<int>. The unrelated class B<double> would hold a pointer to an A<double> etc.


An alternative could be to just store the pointer in a std::any and cast when needed:

#include <any>

template <typename T>
struct A {
    T t;
};

struct B {
    template<class T>
    void store(A<T>& o) {
        a = &o;
    }

    template<class T>
    A<T>& get() {
        return *std::any_cast<A<T>*>(a);
    }

    std::any a;
};

int main() {
    B b;
    
    A<int> ai;
    
    b.store(ai);

    auto& aref = b.get<int>();
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108