Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++의 is_polymorphic 템플릿

<시간/>

이 기사에서는 C++ STL에서 std::is_polymorphic 템플릿의 작동, 구문 및 예에 대해 논의할 것입니다.

is_polymorphic은 C++의 헤더 파일 아래에 있는 템플릿입니다. 이 템플릿은 클래스가 다형성 클래스인지 여부를 확인하고 그에 따라 결과를 true 또는 false로 반환하는 데 사용됩니다.

다형성 클래스란 무엇입니까?

가상 함수가 선언된 추상 클래스에서 가상 함수를 선언하는 클래스입니다. 이 클래스는 다른 클래스에서 선언된 가상 함수의 선언을 가지고 있습니다.

구문

template <class T> is_polymorphic;

매개변수

템플릿은 T 유형의 매개변수만 가질 수 있으며 주어진 유형이 다형성 클래스인지 여부를 확인합니다.

반환 값

Boolean 값을 반환하고, 주어진 유형이 다형성 클래스이면 true, 주어진 유형이 다형성 클래스가 아니면 false를 반환합니다.

예시

Input: class B { virtual void fn(){} };
   class C : B {};
   is_polymorphic<B>::value;
Output: True

Input: class A {};
   is_polymorphic<A>::value;
Output: False

예시

#include <iostream>
#include <type_traits>
using namespace std;
struct TP {
   virtual void display();
};
struct TP_2 : TP {
};
class TP_3 {
   virtual void display() = 0;
};
struct TP_4 : TP_3 {
};
int main() {
   cout << boolalpha;
   cout << "Checking for is_polymorphic: ";
   cout << "\n structure TP with one virtual function : "<<is_polymorphic<TP>::value;
   cout << "\n structure TP_2 inherited from TP: "<<is_polymorphic<TP_2>::value;
   cout << "\n class TP_3 with one virtual function: "<<is_polymorphic<TP_3>::value;
   cout << "\n class TP_4 inherited from TP_3: "<< is_polymorphic<TP_4>::value;
   return 0;
}

출력

위의 코드를 실행하면 다음 출력이 생성됩니다 -

Checking for is_polymorphic:
structure TP with one virtual function : true
structure TP_2 inherited from TP: true
class TP_3 with one virtual function: true
class TP_4 inherited from TP_3: true

예시

#include <iostream>
#include <type_traits>
using namespace std;
struct TP {
   int var;
};
struct TP_2 {
   virtual void display();
};
class TP_3: TP_2 {
};
int main() {
   cout << boolalpha;
   cout << "Checking for is_polymorphic: ";
   cout << "\n structure TP with one variable : "<<is_polymorphic<TP>::value;
   cout << "\n structure TP_2 with one virtual function : "<<is_polymorphic<TP_2>::value;
   cout << "\n class TP_3 inherited from structure TP_2: "<<is_polymorphic<TP_3>::value;
   return 0;
}

출력

위의 코드를 실행하면 다음 출력이 생성됩니다 -

Checking for is_polymorphic:
structure TP with one variable : false
structure TP_2 with one virtual function : true
class TP_3 inherited from structure TP_2 : true