任意の型、個数の引数を受け取るmax
struct gless { typedef bool result_type; template <class T, class U> bool operator() (const T&a, const U&b) const { return a < b; } }; template <typename... T> struct vmax_t; template <typename T> struct vmax_t<T> { typedef T type; }; template <typename T, typename... U> struct vmax_t<T,U...> { typedef typename vmax_t<U...>::type temp_type; typedef decltype(0?T():temp_type()) type; }; template <typename P, typename T> T vmax_if(const P& p, const T& x) { return x; } template <typename P, typename T, typename... U> typename vmax_t<T,U...>::type vmax_if(const P& p, const T& x, const U&... y) { typename vmax_t<U...>::type z = vmax_if(p, y...); return p(z,x)?x:z; } template <typename... U> typename vmax_t<U...>::type vmax(const U&... y) { return vmax_if(gless(), y...); } // 使い方 int main() { std::cout << vmax(14,5,6,4,45.6) << std::endl; }
C++0xの可変個テンプレート引数、decltypeを使っています。
一応、可変個テンプレート引数は、http://www.generic-programming.org/~dgregor/cpp/variadic-templates.html、
decltypeは、GCCのtypeof拡張で代用して動作確認しています。