はじめに
C++20
とか C++17
とか どのようにして数字を決めているのかと思っていたが、西暦の数字だったんですね。なぜ11の次が14なのかと思っていたが疑問が解けた。あと、C++の更新って3年ごとなんですね。
ロベールのC++
複数のtemplate
引数が2つのとき、それぞれ違う typename
を指定しなければならない。
実際にやってみる。
同じ型の引数
#include <iostream>
template <typename TYPE>
TYPE xyz(TYPE x, TYPE y, TYPE z ){
//std::cout << x + y + z <<std::endl;
std::cout << x <<std::endl;
std::cout << y <<std::endl;
std::cout << z <<std::endl;
}
int main(){
double a = 1;
double b = 2;
double c = 3;
xyz(a,b,c);
}
実行結果
1
2
3
では、 double c
を int c
にしてみる。
コンパイラエラー出る
#include <iostream>
template <typename TYPE>
TYPE xyz(TYPE x, TYPE y, TYPE z ){
//std::cout << x + y + z <<std::endl;
std::cout << x <<std::endl;
std::cout << y <<std::endl;
std::cout << z <<std::endl;
}
int main(){
double a = 1;
double b = 2;
int c = 3; //変更
xyz(a,b,c);
}
コンパイルエラー内容
1.cpp: In function 'int main()':
1.cpp:16:12: error: no matching function for call to 'xyz(double&, double&, int&)'
xyz(a,b,c);
^
1.cpp:4:8: note: candidate: template<class TYPE> TYPE xyz(TYPE, TYPE, TYPE)
TYPE xyz(TYPE x, TYPE y, TYPE z ){
^
1.cpp:4:8: note: template argument deduction/substitution failed:
1.cpp:16:12: note: deduced conflicting types for parameter 'TYPE' ('double' and 'int')
xyz(a,b,c);
^
解決方法
解決策
#include <iostream>
template <typename TYPE_X, typename TYPE_Y, typename TYPE_Z> //3つ定義する
void xyz(TYPE_X x, TYPE_Y y, TYPE_Z z ){
std::cout << x + z <<std::endl;
std::cout << x <<std::endl;
std::cout << y <<std::endl;
std::cout << z <<std::endl;
}
int main(){
double a = 1.5;
std::string b = "Hello World";
int c = 3;
xyz(a,b,c);
}
実行結果
4.5
1.5
Hello World
3
std::string
も試してみたが、無事実行できた。これは便利だな。
templateの仕組み
temolateを宣言しただけでは、関数は作られない。引数を渡して初めて、その引数の型の関数が作られる。 template
を宣言することを「インスタンス化」、作られた関数を インスタンス
という。(クラスみたい)
例えば、 void xyz(TYPE_X x, TYPE_Y y, TYPE_Z z )
をいろんな場所で使いたければ、ヘッダファイルを作る必要がある。
1.h
#ifndef TEMPLATE_H
#define TEMPLATE_H
#include <iostream>
template <typename TYPE_X, typename TYPE_Y, typename TYPE_Z> //3つ定義する
void xyz(TYPE_X x, TYPE_Y y, TYPE_Z z ){
std::cout << x + z <<std::endl;
std::cout << x <<std::endl;
std::cout << y <<std::endl;
std::cout << z <<std::endl;
}
#endif //#ifndef TEMPLATE_H
2.cpp
#include "1.h"
#include <iostream>
int main(){
double a = 1.5;
std::string b = "Hello World";
int c = 3;
xyz(a,b,c);
}
なんとなくだけど、テンプレートってかなり便利そう
終わりに
明日は投稿できないかも
おやすみなさい。