开发者

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&g开发者_开发百科t;
struct SmallerOfMandN{
    //and magic happenes here
};

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


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜