[C++] 関数テンプレート

  情報系, プログラミング, C++

テンプレート

「テンプレート」とは,C++の関数のオーバーロード機能において変数型違いだけで同じ処理をするような場合にプログラムを簡略化するとき等に使用する.


関数テンプレート

「関数テンプレート」とは,テンプレート機能を利用した関数のことで,引数や戻り値など型を指定しなくても呼びだれたタイミングでのパラメータの型から,すべての型に自動的に当てはめて実行する関数である.

// template<typename テンプレート型>
// テンプレート型 関数名(テンプレート型 引数名, ...){ ... }
template <typename type>
type sum(type a, type b)
{
    return a+b;
}

int main()
{
    int x;
    double y;
  
    x=sum(10,20);       // int sum(int a, int b)として呼び出される
    y=sum(10.9,11.2);   // double sum(double a, double b)として呼び出される
}

上記のプログラムでは,戻り値,引数をテンプレート型を利用しているが以下のように一部だけ型を固定することができる.

#include <iostream>
template<typename type>
void print(type s)
{
    std::cout << s << std::endl;
}

int main()
{
    int a=10;
    double b=20;
    print(a);       // void print(int a)として呼び出される
    print(b);       // void print(double b)として呼び出される
}

また,複数の型を使用したい場合には,以下のようにすればよい.

#include <iostream>
template<typename type>
void sum_print(type a, type b)
{
    std::cout << a+b << std::endl;
}

template<typename type1, typename type2>
void time_print(type1 a, type2 b)
{
    std::cout << (type1)a*b << std::endl;
}

int main()
{
    int a=10;
    double b=21.5;
    sum_print(a,b);   // ワーニングがでる(sum_printは1つの型しか扱えない)
    time_print(a,b);  // void time_print(int a, double b)として呼び出される
}

関数テンプレートの特殊化

特定の型の場合に,別処理を行いたい場合などに関数テンプレートの特殊化を行うことができる.

#include <iostream>
#include <string>
template<typename type>
void print(type s)
{
    std::cout << "num:" << s << std::endl;
}

// std::string型だけ別処理
template<>
void print(std::string str)
{
    std::cout << "str:"+str << std::endl;
}

int main()
{
    int a=100;
    double b=150;
    std::string s="200";
    print(a);             // num:100 と出力される
    print(b);             // num:150 と出力される
    print(s);             // str:200 と出力される
}

LEAVE A COMMENT