C++基礎学習-2
1917 ワード
関数テンプレート(Function templates)
テンプレート(Templates)を使用すると、すべての可能なデータ型を関数的に再ロードすることなく、任意のデータ型のパラメータを受け入れることができる汎用関数を生成できます.これにより、マクロ(macro)の役割がある程度実現されます.それらのプロトタイプ定義は、次の2つのいずれかになります.
上記の2つのプロトタイプ定義の違いは、キーワードclassまたはtypenameの使用にあります.2つの表現の意味と実行が同じであるため、実際には完全に等価です.
単一パラメータ型の関数テンプレート:
複数パラメータタイプのテンプレート:
クラステンプレート(Class templates)
クラスに共通のタイプに基づいたメンバーを持つことができ、クラス生成時に特定のデータ型を定義する必要はありません.たとえば、次のようにします.
上記で定義したクラスは、2つの任意のタイプの要素を格納するために使用できます.たとえば、クラスの1つのオブジェクトを定義して、2つの整数データ115および36を格納したい場合は、次のように書くことができます.
このクラスでは、次のような他のタイプのデータを格納するために別のオブジェクトを生成できます.
例:
template <> class class_name
テンプレート(Templates)を使用すると、すべての可能なデータ型を関数的に再ロードすることなく、任意のデータ型のパラメータを受け入れることができる汎用関数を生成できます.これにより、マクロ(macro)の役割がある程度実現されます.それらのプロトタイプ定義は、次の2つのいずれかになります.
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
上記の2つのプロトタイプ定義の違いは、キーワードclassまたはtypenameの使用にあります.2つの表現の意味と実行が同じであるため、実際には完全に等価です.
単一パラメータ型の関数テンプレート:
#include <iostream>
using namespace std;
template <class T> T GetMax(T a, T b){
return (a>b?a:b);
}
int main(int argc, char *argv[]) {
int i = 10, j = 20;
cout << GetMax(i,j) << endl;
}
複数パラメータタイプのテンプレート:
#include <iostream>
using namespace std;
template <class T, class U> T GetMax(T a, U b){
return (a>b?a:b);
}
int main(int argc, char *argv[]) {
int i = 100;
long j = 20;
cout << GetMax(i,j) << endl;
}
クラステンプレート(Class templates)
クラスに共通のタイプに基づいたメンバーを持つことができ、クラス生成時に特定のデータ型を定義する必要はありません.たとえば、次のようにします.
#include <iostream>
using namespace std;
template <class T>
class People {
public:
T name ;
T age;
public:
People(T first, T second){
name = first;
age = second;
}
};
int main(int argc, char *argv[]) {
People<int>p(10, 20);
cout << p.name << endl;
cout << p.age << endl;
}
上記で定義したクラスは、2つの任意のタイプの要素を格納するために使用できます.たとえば、クラスの1つのオブジェクトを定義して、2つの整数データ115および36を格納したい場合は、次のように書くことができます.
pair<int>p (115, 36);
このクラスでは、次のような他のタイプのデータを格納するために別のオブジェクトを生成できます.
pair<float>p (3.0, 2.18);
, inline 。 , template <... >。
例:
template <> class class_name