C++ 如何在模板元编程中进行小于比较?
周一我被问到这个问题,我不知道该怎么回答。因为我不知道,我现在非常想知道。好奇心害死了这只猫。给定两个整数,在编译时返回较小的整数C++ 如何在模板元编程中进行小于比较?,c++,templates,metaprogramming,C++,Templates,Metaprogramming,周一我被问到这个问题,我不知道该怎么回答。因为我不知道,我现在非常想知道。好奇心害死了这只猫。给定两个整数,在编译时返回较小的整数 template<int M, int N> struct SmallerOfMandN{ //and magic happenes here }; 模板 结构SmallerOfMandN{ //这里发生了奇迹 }; 有什么建议或者怎么做?(将于今晚开始阅读。)这被称为两个数字中的最小值,您不需要像mpl这样的世界重量级库来做这样的事情: t
template<int M, int N>
struct SmallerOfMandN{
//and magic happenes here
};
模板
结构SmallerOfMandN{
//这里发生了奇迹
};
有什么建议或者怎么做?(将于今晚开始阅读。)这被称为两个数字中的最小值,您不需要像
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;
}
模板
结构编译时间分钟
{
静态常数小于等于M
当然,如果是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);
}
constexpr int compile\u time\u min(int M,int N)
{
返回M
就这样?一个简单的三元运算符?我不知道它能在编译时像那样工作。多谢!我必须再等6分钟才能接受这个答案。给自己一个“C++模板-完整指南”的拷贝,也许“现代C++设计”真正开始这个主题: