views:

112

answers:

1

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.)

+13  A: 

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);
}
AraK
That's it? A simple ternary operator? I had no idea it could work in compile time like that. Thanks much! I have to wait another 6 min. to accept this answer.
wheaties