代码之家  ›  专栏  ›  技术社区  ›  wheaties

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

  •  8
  • wheaties  · 技术社区  · 15 年前

    星期一我被问到这个问题,我不知道该怎么回答。因为我不知道,我现在非常想知道。好奇心害死了这只猫。给定两个整数,在编译时返回较小的整数。

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

    Boost MPL 今晚。)

    1 回复  |  直到 15 年前
        1
  •  17
  •   Khaled Alshaya    15 年前

    这被称为两个数的最小值,你不需要像这样的世界重量级库 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);
    }