Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a less than comparison in template meta-programming?

I had this question asked of me on Monday and for the life of me I don't know how to answer. Since I don't know, I now want to very much find out. Curiosity is killing this cat. Given two integers, return the lesser at compile time.

template<int M, int N>
struct SmallerOfMandN{
    //and magic happenes here
};

Got pointers or how to do it? (Will start reading Boost MPL tonight.)

like image 569
wheaties Avatar asked Jul 22 '10 13:07

wheaties


1 Answers

That is called the minimum of two numbers, and you don't need world heavy weight library like mpl to do such a thing:

template <int M, int N>
struct compile_time_min
{
    static const int smaller =  M < N ? M : N;
};

int main()
{
    const int smaller = compile_time_min<10, 5>::smaller;
}

Of course if it was C++0x you could easily say:

constexpr int compile_time_min(int M, int N)
{
    return M < N ? M : N;
}

int main()
{
    constexpr int smaller = compile_time_min(10, 5);
}
like image 179
Khaled Alshaya Avatar answered Oct 20 '22 02:10

Khaled Alshaya