天天看點

利用C++11特性實作最大值和最小值的模闆函數

直接上代碼

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