LoginSignup
2
0

More than 3 years have passed since last update.

関数テンプレート

Last updated at Posted at 2019-06-21

関数テンプレートを使うと、型が異なる場合の関数定義をテンプレートとして、まとめて定義できる

main.cpp
#include<iostream>

using namespace std;
//テンプレート宣言
template <typename T>
T add(T x1, T x2) { return x1 + x2; }
int main()
{
    int a = add(1, 2);//実行結果:3
    //float b = add(1.0F, 2);//第一引数がfloat型,第二引数がint型だから判断できない
    float b = add(1.0F, 5.0F);//これなら、型が判断できるからOK‼//実行結果:6

    cout << a <<endl;
    cout << b;
}

引数の型(int,float)からT型(template T)を推測する
注意 引数の型が2つ混在すると、型の判断ができなくなって、エラーになる

型が混在する場合、明示的具現化を行う

main.cpp
#include<iostream>

using namespace std;
template <typename T>
T add(T x1, T x2) { return x1 + x2; }

template<typename T1,typename T2>
T2 average(T1 x1, T1 x2) { return (x1 + x2) / 2.0; }
int main()
{
    //明示的具現化
    int c = add<int>(50, 60.0F);//計算結果がint型で返ってくる
    cout << c << endl;//結果110
    double d = average<float, double>(10.0F, 20.0F);
    cout << d << endl;//結果15.00000以下略
}

cのように、型を関数名の後に指定してあげると、その型で返すことができる
dはfloat型で受け取った値をdouble型で返している( T1→float,T2→double)
返り値がT2なので、double型となる

main.cpp
#include<iostream>

//名前空間
using namespace std;

template <typename T3>
bool equal(T3 a, T3 b)//二つの値が等しいかどうか比較する
{
    return a == b;
}
int main()
{
    int a = 3;
    int b = 3;
    cout<<equal(a, b)<<endl;//trueが返ってくる

    //文字列の場合
    //文字列リテラル同士の比較
    cout<<equal("ABC", "ABC")<<endl;//trueが返ってくる

    //文字列のポインタ同士の比較
    char str1[10] = "ABC";
    char str2[10] = "ABC";
    cout<<equal(str1, str2)<<endl;//falseが返ってくる


}

なぜリテラル同士だと正しく結果が返ってくるのに、文字列ポインタ同士だと、正しい結果が返ってこないのか
文字列ポインタ同士だと、アドレスの比較を行ってしまうからです
文字列ポインタ同士を比較したい場合→完全特殊化を行う

main.cpp
#include<iostream>

//名前空間
using namespace std;

//完全特殊化
template<>
bool equal(char* A, char* B)//引数で指定している方の場合のみ、この動作を行う
{
    return strcmp(A, B) == 0;//strcmp関数で文字列の大小を比較(A<Bなら負の値、A==Bなら0、A>Bなら正の値が返ってくる)
}
int maih()
{
       char str1[10] = "ABC";
    char str2[10] = "ABC";
    cout << equal(str1, str2) << endl;//trueが返ってくる


}

完全特殊化を行うと引数で指定した型の場合のみ、その動作を行ってくれる

2
0
15

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