如何在模板元编程中进行比较?

时间:2010-07-22 13:11:13

标签: c++ templates metaprogramming

星期一我问过这个问题而且我的生活中我不知道如何回答。由于我不知道,我现在想要非常了解。好奇心正在杀死这只猫。给定两个整数,在编译时返回较小的整数。

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

有指针或怎么做? (今晚将开始阅读Boost MPL。)

1 个答案:

答案 0 :(得分:17)

这被称为两个数字的最小值,并且您不需要像mpl这样的世界重量级库来做这样的事情:

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

当然,如果它是C ++ 0x,你可以很容易地说:

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

int main()
{
    constexpr int smaller = compile_time_min(10, 5);
}
相关问题