How to check whether two objects belong to the same class in std c using templates or any function?
class A{};
class B{};
int main()
{
B b1, b2;
A a1,a2;
cout<< issame(a1,b1)<< endl;
cout<< issame(a1,a2)<< endl;
}
CodePudding user response:
C is statically typed, B
and A
are different types. Maybe its just a matter of your code not demonstrating the use case, but in your code there is no need to "check", you already know that B
is not A
. In a template the situation is different, you can have for example:
template <typename U, typename V>
void foo(U u, V v);
and then U
and V
can be either different types or the same. To check if they are the same you can use the type trait std::is_same_v<U,V>
CodePudding user response:
You can define a function issame
like
#include <type_traits>
//...
template<typename S, typename T>
constexpr bool issame(S, T) {
return std::is_same<S, T>::value;
}
and use it just like in your example.
std::cout << issame(a1,b1) << std::endl; // outputs "0"
std::cout << issame(a1,a2) << std::endl; // outputs "1"