闲来无事,试试用arg_list查找n个数字中的最大者. 又因为本人喜欢模板, 所以就早早的写了以下代码, 没有经过严格测试.
/******************************************************************************* * 版权所有: * 模 块 名: * 文 件 名:template_max_value.cpp * 实现功能:取不定数目的数值中的最大值 * 作 者:leaker * 版 本:V1.0 * 日 期:2013.11.07 * 联系方式:xiao13149920@foxmail.com ********************************************************************************/ // template_max_value.cpp #include<stdarg.h> #include<iostream> using namespace std; template<typename T> struct trait_type; #if 0 template<> struct trait_type<char> { typedef char value_type; }; template<> struct trait_type<unsigned char> { typedef unsigned char value_type; }; template<> struct trait_type<short> { typedef short value_type; }; template<> struct trait_type<unsigned short> { typedef unsigned short value_type; }; #endif template<> struct trait_type<int> { typedef int value_type; }; template<> struct trait_type<unsigned int> { typedef unsigned int value_type; }; template<> struct trait_type<long> { typedef long value_type; }; template<> struct trait_type<unsigned long> { typedef unsigned long value_type; }; template<> struct trait_type<long long> { typedef long long value_type; }; template<> struct trait_type<unsigned long long> { typedef unsigned long long value_type; }; #if 0 template<> struct trait_type<float> { typedef float value_type; }; #endif template<> struct trait_type<double> { typedef double value_type; }; template <typename T> typename trait_type<T>::value_type GetMaxValue(int numarg, ...) { va_list args; va_start(args, numarg); typedef typename trait_type<T>::value_type value_type; value_type ret = va_arg(args, value_type); while(--numarg) { value_type arg = va_arg(args, value_type); (ret < arg) && (ret = arg); } va_end(args); return ret; } int main() { int a = 9; int b = 19; int c = 29; int d = 39; std::cout<<GetMaxValue<int>(12,c,d,1,2,3,4,5,6,7,8,9,static_cast<int>(199.990))<<std::endl; std::cout<<GetMaxValue<double>(10 ,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.9,199.990)<<std::endl; std::cout<<GetMaxValue<unsigned int>(12,c,d,1,2,3,4,5,6,7,8,9,static_cast<unsigned int>(199.990))<<std::endl; return 0; }
或者有人疑惑为什么对char/short/float的trait_type注释起来. 原因是因为
When you call a function with a variable argument list (which is generally a bad idea in C++), then anyfloat
expressions are automatically promoted (converted) to double
, and any char
(any of the three flavours) and short
(two flavours) are promoted to int
. Therefore, as the error message says, you cannot expect va_arg()
to collect a float
or a char
type; you need to collect a double
orint
and coerce the result if necessary.
不足之处, 对于调用GetMaxValue<T>时,请确定好数据类型,并且请保证所传的比较数字的数据类型与T保持一致.若是不一致,请先转换.