2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C++】基礎を学ぶ㉑~テンプレート~

Last updated at Posted at 2022-07-18

テンプレート

テンプレートとは、構造体や関数のを一般化するための仕組み
関数テンプレートは処理の内容のひな型を作って、それを異なるデータ型に当てはめる

関数テンプレートの構文

template <typename テンプレート引数>
返り値の型 関数名(引数の型 引数名...){
  // 処理内容
}

サンプルプログラム

#include <iostream>
using namespace std;

template <typename T>
T square(T x){
  return x * x;
}

int main() {
  cout << square(3) << endl;
  cout << square(1.5) << endl;
  return 0;
}
9
2.25

クラステンプレート

クラステンプレートとは、メンバ変数の型を一般化して作成するクラスのこと

クラステンプレートの構文

template <typename テンプレート引数>
class クラス名{
  // クラスの内容
}

サンプルプログラム

#include <iostream>
using namespace std;

template <typename T>
class Point {
  public:
    T x;
    T y;
    Point(T arg1, T arg2){
      x = arg1;
      y = arg2;
    }
    void print() {
      cout << "(" << x << ", " << y << ")" << endl;
    }
};

int main() {
  Point<int> point1(1,2);
  Point<double> point2(1.2,3.4);
  point1.print();
  point2.print();
  return 0;
}
(1, 2)
(1.2, 3.4)

次の記事

【C++】基礎を学ぶ㉒~STL~

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?