【问题标题】:How to make a less than comparison in template meta-programming?如何在模板元编程中进行小于比较?
【发布时间】:2010-07-22 13:11:12
【问题描述】:

周一有人问我这个问题,我一生不知道如何回答。既然不知道,我现在很想知道。好奇心正在杀死这只猫。给定两个整数,在编译时返回较小的。

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

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

【问题讨论】:

  • 获取一份“C++ 模板 - 完整指南”“现代 C++ 设计” 的副本,以便真正开始学习该主题: )

标签: c++ templates metaprogramming


【解决方案1】:

这叫做两个数的最小值,你不需要像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);
}

【讨论】:

  • 就这样?一个简单的三元运算符?我不知道它可以像这样在编译时工作。非常感谢!我还要再等6分钟。接受这个答案。
猜你喜欢
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多