জাভার মতো C++-এ সরাসরি instanceof অপারেটর নেই। কিন্তু C++11-এ std::is_base_of<Base, T> ব্যবহার করে বেস ক্লাস চেক করা যায়, তবে এটি রানটাইম পলিমরফিজম সাপোর্ট করে না।
সবচেয়ে কাছাকাছি সমাধান হলো dynamic_cast ব্যবহার করা। এটি পলিমরফিক পয়েন্টার ও RTTI (Run-Time Type Information) সক্রিয় থাকলে কাজ করে। কাস্ট ব্যর্থ হলে নাল পয়েন্টার রিটার্ন করে।
উদাহরণ কোড
#include <iostream>
using namespace std;
template<typename Base, typename T>
inline bool instanceof(const T* ptr) {
return dynamic_cast<const Base*>(ptr) != nullptr;
}
class Parent {
public:
virtual ~Parent() {}
virtual void foo() { cout << "Parent\n"; }
};
class Child : public Parent {
public:
virtual void foo() { cout << "Child\n"; }
};
class AnotherClass {};
int main() {
Parent p;
Child c;
AnotherClass a;
Parent* ptr1 = &p;
Child* ptr2 = &c;
AnotherClass* ptr3 = &a;
if (instanceof<Parent>(ptr1))
cout << "p is an instance of Parent" << endl;
else
cout << "p is not an instance of Parent" << endl;
if (instanceof<Parent>(ptr2))
cout << "c is an instance of Parent" << endl;
else
cout << "c is not an instance of Parent" << endl;
if (instanceof<Child>(ptr2))
cout << "c is an instance of Child" << endl;
else
cout << "c is not an instance of Child" << endl;
if (instanceof<Child>(ptr1))
cout << "p is an instance of Child" << endl;
else
cout << "p is not an instance of Child" << endl;
if (instanceof<AnotherClass>(ptr2))
cout << "c is an instance of AnotherClass" << endl;
else
cout << "c is not an instance of AnotherClass" << endl;
return 0;
}
আউটপুট
p is an instance of Parent c is an instance of Parent c is an instance of Child p is not an instance of Child c is not an instance of AnotherClass
শর্তাবলী: বেস ক্লাসে কমপক্ষে একটি ভার্চুয়াল ফাংশন (যেমন ভার্চুয়াল ডেস্ট্রাক্টর) থাকতে হবে এবং কম্পাইলার অপশনে RTTI অ্যাক্টিভ থাকতে হবে।