C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

C++のis_polymorphicテンプレート


この記事では、C++STLでのstd::is_polymorphicテンプレートの動作、構文、および例について説明します。

is_polymorphicは、C++のヘッダーファイルの下にあるテンプレートです。このテンプレートは、クラスがポリモーフィッククラスであるかどうかを確認し、それに応じて結果をtrueまたはfalseで返すために使用されます。

ポリモーフィッククラスとは何ですか?

仮想関数が宣言されている抽象クラスから仮想関数を宣言するクラス。このクラスには、他のクラスで宣言された仮想関数の宣言があります。

構文

template <class T> is_polymorphic;

パラメータ

テンプレートはタイプTのパラメーターのみを持つことができ、指定されたタイプがポリモーフィッククラスであるかどうかを確認します。

戻り値

ブール値を返します。指定された型がポリモーフィッククラスの場合は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

  1. C++での構造とクラス

    C ++では、構造とクラスは基本的に同じです。しかし、いくつかの小さな違いがあります。これらの違いは以下のようなものです。 クラスメンバーはデフォルトでプライベートですが、構造体のメンバーはパブリックです。違いを確認するために、これら2つのコードを見てみましょう。 サンプルコード #include <iostream> using namespace std; class my_class {    int x = 10; }; int main() {    my_class my_ob;    cout <&l

  2. C++のローカルクラス

    関数内で宣言されたクラスは、その関数に対してローカルであるため、C++ではローカルクラスと呼ばれます。 ローカルクラスの例を以下に示します。 #include<iostream> using namespace std; void func() {    class LocalClass {    }; } int main() {    return 0; } 上記の例では、func()は関数であり、クラスLocalClassは関数内で定義されています。したがって、ローカルクラスとして知られています。 ローカルクラ