利用C++11特性实现最大值和最小值的模板函数

版权声明:本文为博主原创文章,如有需要,可以随意转载,请注明出处。 https://blog.csdn.net/xunye_dream/article/details/82929980

直接上代码

template<typename T, typename U>
inline auto max(T const& x, U const& y) -> decltype(sizeof(x) > sizeof(y) ? x : y)
{
	return x > y ? x : y;
}

template<typename T, typename U>
inline auto min(T const& x, U const& y) -> decltype(sizeof(x) > sizeof(y) ? x : y)
{
	return x < y ? x : y;
}
#include <iostream>
#include <typeinfo>
#include "max_and_min.hpp"

int main(int argc, char **argv)
{
	int a = 10;
	long b = 2;
	auto value = ::max(a, b);
	std::cout << value << std::endl;
	std::cout << typeid(value).name() << std::endl;

	return 0;
}

输出结果:

10
l

猜你喜欢

转载自blog.csdn.net/xunye_dream/article/details/82929980
今日推荐