কম্পিউটার

C++ instanceof এর সমতুল্য


C++ এর কোনো সরাসরি পদ্ধতি নেই যে কোনো একটি অবজেক্ট কোনো ক্লাস টাইপের একটি উদাহরণ কিনা তা পরীক্ষা করার জন্য। জাভাতে, আমরা এই ধরনের সুবিধা পেতে পারি।

C++11-এ, আমরা is_base_of নামে একটি আইটেম খুঁজে পাই। এটি প্রদত্ত শ্রেণীটি প্রদত্ত বস্তুর একটি বেস কিনা তা পরীক্ষা করবে। কিন্তু, প্রদত্ত শ্রেণীর উদাহরণটি সেই ফাংশনটি ব্যবহার করে কিনা তা যাচাই করে না।

"ইনস্ট্যান্সফ" এর মতো নিকটতম সম্ভাব্য কার্যকারিতা ডাইনামিক_কাস্ট (এক্সপ্রেশন) ব্যবহার করে অর্জন করা যেতে পারে . এটি প্রদত্ত মানটিকে নির্দিষ্ট প্রকারের মধ্যে গোপন করার চেষ্টা করে এবং ফলাফল প্রদান করে। কাস্ট ব্যর্থ হলে এটি একটি নাল পয়েন্টার প্রদান করে। এটি শুধুমাত্র পলিমরফিক পয়েন্টারগুলির জন্য কাজ করে এবং যখন কম্পাইলার RTTI সক্রিয় থাকে।

উদাহরণ কোড

#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 () { std::cout << "Parent\n"; }
};

class Child : public Parent {
   public:
   virtual void foo() { std::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 the class Parent" << endl;
   } else {
      cout << "p is not an instance of the class Parent" << endl;
   }

   if(instanceof<Parent>(ptr2)) {
      cout << "c is an instance of the class Parent" << endl;
   } else {
      cout << "c is not an instance of the class Parent" << endl;
   }

   if(instanceof<Child>(ptr2)) {
      cout << "c is an instance of the class Child" << endl;
   } else {
      cout << "c is not an instance of the class Child" << endl;
   }

   if(instanceof<Child>(ptr1)) {
      cout << "p is an instance of the class Child" << endl;
   } else {
      cout << "p is not an instance of the class Child" << endl;
   }

   if(instanceof<AnotherClass>(ptr2)) {
      cout << "c is an instance of AnotherClass class" << endl;
   } else {
      cout << "c is not an instance of AnotherClass class" << endl;
   }
}

আউটপুট

p is an instance of the class Parent
c is an instance of the class Parent
c is an instance of the class Child
p is not an instance of the class Child
c is not an instance of AnotherClass class

  1. C++ এ একাধিক উত্তরাধিকার

  2. C++ এ স্থানীয় ক্লাস

  3. C++ বন্ধু কীওয়ার্ডের C# সমতুল্য কী?

  4. C# এ BigInteger ক্লাস