// // sum : 可変長引数関数のサンプル // // g++ -std=c++11 sum.cpp #include //////////////////////////////////////////////////////////////// //// 整数の合計 //////////////////////////////////////////////////////////////// // 末端 isum inline int isum() { return 0; } // 再帰呼び出し isum template int isum(const First& first, const Rest&... rest) { return first + isum(rest...); } //////////////////////////////////////////////////////////////// //// 任意の型の合計 //////////////////////////////////////////////////////////////// template Ret any_sum() { return Ret(); } template Ret any_sum(const First& first, const Rest&... rest) { return first + any_sum(rest...); } //////////////////////////////////////////////////////////////// //// 文字列の結合 //////////////////////////////////////////////////////////////// #include inline void concat_internal(std::stringstream &sout) { } template void concat_internal(std::stringstream &sout, const First& first, const Rest&... rest) { sout << first; concat_internal(sout, rest...); } template std::string concat(const Args&... args) { std::stringstream sout; concat_internal(sout, args...); return sout.str(); } //////////////////////////////////////////////////////////////// //// 使用例 //////////////////////////////////////////////////////////////// using namespace std; int main() { cout << isum(1, 2, 3, 4) << endl; // 10 cout << isum(1.0, 2.2, 3.3, 4.9) << endl; // 10 // = 1.0 + 2 + 3 + 4 + isum() cout << any_sum(1.0, 2.2, 3.3, 4.9) << endl; // 10 cout << any_sum(1.0, 2, 3.3, 4.9) << endl; // 11.2 cout << any_sum("Hello", " ", "world", "!") << endl; // "Hello world!" // cout << any_sum("Hello ", "world", 3) << endl; // コンパイルエラー cout << concat("Hello ", "world ", 3, " ", 1.2) << endl; // "Hello world 3 1.2" return 0; }