Re: Is there a min function that accepts any number of arguments?
Peng Yu wrote:
Hi,
I'm wondering if there is a min function (in boost, maybe?) that
accepts any number of arguments? std::min only accepts two arguments.
If I want to get the minimum number out of many, I have use std::min
many times, which is not convenient.
Well, if you really want it:
----------------
namespace peng_yu
{
template<typename T>
struct tmp_min_t
{
const T &item;
tmp_min_t(const T &n) : item(n) {}
operator const T& () const { return item; }
};
struct minimum_t {} minimum;
template<typename T>
inline tmp_min_t<T> operator , (minimum_t, const T &x)
{
return tmp_min_t<T>(x);
}
template<class T>
inline tmp_min_t<T> operator , (tmp_min_t<T> a, const T &x)
{
if (a.item<=x) return a;
else return tmp_min_t<T>(x);
}
}
#define MIN(...) (peng_yu::minimum,__VA_ARGS__)
#include <iostream>
int main()
{
std::cout
<< MIN(6,5,4,5,1,5,3,5,7,4,3,4,6,8,5,3,2,-23,5,2,2,4,6,4,4,3,4)
<< std::endl;
}
--------------
You'll need a compiler with C99-style variadic macro support though
(which is supported by most compilers I am aware of), or preprocess
your source accordingly.