Skip to content

Instantly share code, notes, and snippets.

@chomado
Created August 4, 2014 01:12
Show Gist options
  • Save chomado/77ef5a027a5aef4d8b4d to your computer and use it in GitHub Desktop.
Save chomado/77ef5a027a5aef4d8b4d to your computer and use it in GitHub Desktop.
テンプレート練習。明示的な特殊化
/* 配列の全要素の最小値を求める関数テンプレートと明示的な特殊化 */
#include <iostream>
#include <cstring>
using namespace std;
/* 配列a全要素の最小値を求める */
template <typename Type> Type minof(const Type a[], int n)
{
Type min = a[0];
for (int i=1; i<n; i++) {
if (a[i] < min) {
min = a[i];
}
}
return min;
}
/* 配列aの全要素の最小値を求める (const char*型の特殊化)*/
// template <> 返却型 func<T>(引数) { 関数本体 }
template <> const char* minof<const char*>(const char* const a[], int n)
{
const char* min = a[0];
for (int i=1; i<n; i++) {
if (a[i] < min) {
min = a[i];
}
}
return min;
}
int main()
{
const int na = 5;
int a[na];
const int ns1 = 3;
char* s1[ns1];
const char* s2[] = {"OS X", "Windows", "Linux", "Unix"};
int ns2 = sizeof(s2) / sizeof(s2[0]);
cout << "int型配列aの要素の値を入力せよ" << endl;
for (int i=0; i<na; i++) {
cout << "a[" << i << "]: ";
cin >> a[i];
}
cout << "文字列配列s1の要素の値を入力せよ" << endl;
for (int i=0; i<ns1; i++) {
char temp[64];
cout << "s[" << i << "]: ";
cin >> temp[i];
s1[i] = new char[strlen(temp) +1];
strcpy(s1[i], temp);
}
cout << "文字列配列s2の要素は以下の通りです" << endl;
for (int i=0; i<ns2; i++) {
cout << "s2[" << i << "] = " << s2[i] << endl;
}
cout << "配列aの最小値は" << minof(a, na) << "です" << endl;
cout << "配列s1の最小値は" << minof<const char*>(s1, ns1) << "です" << endl;
cout << "配列s2の最小値は" << minof<const char*>(s2, ns2) << "です" << endl;
for (int i=0; i<ns1; i++) {
delete s1[i];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment