Menu
CoddyTech

関数テンプレート

Coddyの「C開発者のためのC++」コースのレッスン 25/48。

Cでは、再利用可能な処理を書くためにマクロやvoidポインターがよく使われますが、その際に型チェックの一部が失われます。C++のテンプレートは、インスタンス化されると型付きの関数やクラスを生成します。各翻訳単位が必要な特殊化をインスタンス化できるよう、定義は通常ヘッダーに記述します。

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int twice_int(int n){return n+n;}
int main(void){
printf("%d\n",twice_int(3));
return 0;
}

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
template<class T>T twice(T value){return value+value;}
int main(){
std::cout<<twice(3)<<" "<<twice(std::string("ha"))<<"\n";
}

各プログラムを個別にトレースしてください。これらの例は、課題とは異なる操作やデータを使って概念を示しています。ソースコードと変換後の出力が一致するとは限りません。

challenge icon

チャレンジ

簡単

入力: 2つの整数。ヘッダーファイルで順序付け可能な型に対する smaller を実装してください。独立したテストで使用される文字列も含め、より小さい方の引数を返してください。

exercise.hpp と exercise.cpp で宣言された API を実装してください。どちらのファイルも編集できますが、公開シグネチャは変更しないでください。ロックされた main.cpp は標準入力を読み取り、API を直接呼び出します。また、記載されている箇所では公開 API の動作も独立して確認します。API 内では出力せず、戻り値を返してください。整数の入力値と結果は符号付き int の範囲内です。特に記載がない限り、テキストは ASCII です。

自分で試してみよう

#include "exercise.hpp"
#include <iostream>
int main(){
{if(smaller(std::string("z"),std::string("a"))!="a")return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int a,b;in>>a>>b;std::cout<<smaller(a,b)<<"\n";
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C開発者のためのC++のすべてのレッスン

自分で練習してみよう: C++オンラインコンパイラ