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.
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>();
}
}
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(charconst selector) {
if (selector == 'i') return std::make_unique<A<int>>();
if (selector == 'f') return std::make_unique<A<float>>();
elsereturnnullptr;
}
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