Pointer to Template classes objects

How can a pointer can point to different instance of same template class.?
i am enclosing my code snippet below, where objA pointer should be able to point to object of A with different template parameter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Template<class T>
Class A
{
T data;
Public void SetData(T value)
{
}
}

Class BinderA
{
A* objA;   ……………// pointer to instance of A
BinderA(char type)
{
Switch(type)
{
Case ‘I’ :  objA =new  A<int>();     //  creating instance of class A based on type

Case ‘f’ :  objB=new A<float>();
}
}
Last edited on
This looks like an XY problem ( http://xyproblem.info ). What problem are you trying to solve?

To proceed anyways, C++'s templates are not merely generics. the two classes A<T> and A<U> are completely unrelated from the type system's perspective. This is mostly because explicit template specializations make it impossible to guarantee a common interface between any two A<T> and A<U>.

Codify that (perhaps empty) interface with a base class. Of course you are still responsible for knowing the dynamic type of the result. It can be retrieved with RTTI.

1
2
3
4
5
6
7
8
9
10
struct B { virtual ~B() = default; };
template <typename T> struct A: B {
  void set_data(T value) { ... }
}; 

std::unique_ptr<B> make_b(char const selector) {
  if (selector == 'i') return std::make_unique<A<int>>();
  if (selector == 'f') return std::make_unique<A<float>>();
  else return nullptr;
}


Related threads
http://www.cplusplus.com/forum/beginner/219523/
http://www.cplusplus.com/forum/beginner/217282/#msg1005435
Last edited on
The problem is,
i am trying to expose C++ template class to python using boost::Python. Since we cant expose template class directly to python, i am creating binder class for that class and exposing the binder class.
So in above code class A is template class which is to be exposed to python.
BinderA is a wrapper class, where i am passing char argument in constructor and based on this char argument ,object of class A is created.So, a pointer to A is required in BinderA, which can hold the reference of any instance of template A .

Please let me know if there is any other best solution to expose C++ template class to python using boost framework.
Thanks

Class templates are neither classes nor types, so you can't create a variable of type "pointer to A".
You should supply a base class.

Note also that my example above was missing a virtual destructor. It's fixed now.
Topic archived. No new replies allowed.