I have a program as follows (It's a recreation of my actual issue):
#include <iostream>
class A {
public:
void printA () {
std::cout << "AA" << std::endl;
}
};
class B {
public:
void printB () {
std::cout << "BB" << std::endl;
}
};
template <typename T>
class C {
public:
void printC () {
T obj;
if (std::is_same<A, T>::value) {
obj.printA ();
} else if (std::is_same<B, T>::value) {
obj.printB ();
}
}
};
int main () {
C<A> c1;
C<B> c2;
c1.printC ();
c2.printC ();
return 0;
}
On compilation, I am getting the following errors:
handle_different_typenames.cpp: In instantiation of ‘void C<T>::printC() [with T = A]’:
handle_different_typenames.cpp:34:16: required from here
handle_different_typenames.cpp:25:17: error: ‘class A’ has no member named ‘printB’; did you mean ‘printA’?
25 | obj.printB ();
| ~~~~^~~~~~
| printA
handle_different_typenames.cpp: In instantiation of ‘void C<T>::printC() [with T = B]’:
handle_different_typenames.cpp:35:16: required from here
handle_different_typenames.cpp:23:17: error: ‘class B’ has no member named ‘printA’; did you mean ‘printB’?
23 | obj.printA ();
| ~~~~^~~~~~
| printB
How to solve this issue?
Ideally, I want the situation where if T = A, the code inside else if (std::is_same<B, T>::value) {...} should not be checked at compile time. Similarly, if T = B, the code inside if (std::is_same<A, T>::value) {...} should not be checked at compile time.
Thanks in advance!