'check whether two objects belongs to same class in C++
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;
}
Solution 1:[1]
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>
Solution 2:[2]
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"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 463035818_is_not_a_number |
| Solution 2 | Jakob Stark |
