自分用覚え書き:特殊化テンプレート関数の記述方法
#include <iostream> #include <string> template<typename T> int compfunc(T a, T b) { std::cout << "compfunc(T a, T b)" << std::endl; return a - b; } template<> int compfunc<std::string>(const std::string& a, const std::string& b) { std::cout << "compfunc(const std::string& a, const std::string& b)" << std::endl; return a.compare(b); } template<> int compfunc<char*>(const char* a, const char* b) { std::cout << "compfunc(const char* a, const char* b)" << std::endl; return strcmp(a , b); } template<> int compfunc<double>(double a, double b) { std::cout << "compfunc(double a, double b)" << std::endl; return a - b; } template<> int compfunc<int>(int a, int b) { std::cout << "compfunc(int a, int b)" << std::endl; return a - b; } int main(int argc, char* argv[]) { std::string a("111"), b("222"); compfunc(1, 2); compfunc(0.0, 0.0); compfunc<char*>("11111", "22222"); compfunc<std::string>(a, b); return 0; }
実行結果:
D:\TEMP>bcc32 File1.cpp CodeGear C++ 5.93 for Win32 Copyright (c) 1993, 2007 CodeGear File1.cpp: 警告 W8057 File1.cpp 44: パラメータ 'argc' は一度も使用されない(関数 main(int,char * *) ) 警告 W8057 File1.cpp 44: パラメータ 'argv' は一度も使用されない(関数 main(int,char * *) ) Turbo Incremental Link 5.80 Copyright (c) 1997-2007 CodeGear D:\TEMP>File1 compfunc(int a, int b) compfunc(double a, double b) compfunc(const char* a, const char* b) compfunc(const std::string& a, const std::string& b)
う〜ん、特殊化テンプレート関数の記述方法はわけわかめだ。特に3つめと4つめ。
曖昧さ排除のためなんだろうけど、わざわざ引数を追加するのは何故なんだろう。
C++ Templates: The Complete Guideの日本語訳マダー(AA略
cppll MLで話のタネとして出ているけど、未だに日本語訳出ていないから挫折覚悟で洋書を買うしかないかも。
関連書籍っぽいC++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond (C++ in Depth Series)とジェネレーティブプログラミング (IT Architects’Archive CLASSIC MODER)もかなり濃そうだ。
10:00追記:
゚ *. (_ヽ + 。 ' * ∧__∧| | + C++ TemplatesとC++ Template Metaprogrammingをまとめて . (´∀` / / 。 イヤッホォォオォオウ!! + y'_ イ * 〈_,)l | * 。 ガタン lll./ /l | lll + Λ_Λ /,'≡ヽ::)、 数ヶ月以内に日本語訳出るなよ。  ̄ ̄ ̄ ゙̄-' ̄`--´ ̄ ̄ ̄ ̄ ̄ ∧ ∧. _::::。・._、_ ゚ ・ あれ、ジェネレーティブプログラミングは? /:彡ミ゛ヽ;)(m,_)‐-(<_,` )-、 * あと、日本語訳が出たらもちろんですよね。 / :::/:: ヽ、ヽ、 ::iー-、 .i ゚ + / :::/;;: ヽ ヽ ::l ゝ ,n _i l  ̄ ̄ ̄(_,ノ  ̄ ̄ ̄ヽ、_ノ ̄ ̄E_ )__ノ