如何消除“除以0"模板代码错误 [英] How to eliminate "divide by 0" error in template code

查看:31
本文介绍了如何消除“除以0"模板代码错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一对整数模板参数来指定比率,因为我不能使用双精度数作为模板参数.转换为双精度数时受到保护,不会被三元数除以零.这在早期版本的编译器中有效,但 Visual Studio 2013 出现错误:

I'm using a pair of integer template parameters to specify a ratio, since I can't use a double as a template parameter. The conversion into a double is protected against divide-by-zero with a ternary. This worked in an earlier version of the compiler, but Visual Studio 2013 gives an error:

error C2124: divide or mod by zero

这是代码的简化版本:

template<int B1, int B2>
class MyClass
{
    const double B = (B2 == 0) ? 0.0 : (double) B1 / (double) B2;
    // ...
};

MyClass<0, 0> myobj;

我真的希望 B 在它为零时使用它的表达式进行优化,所以我需要单行定义.我知道我可以只使用模板参数 <0, 1> 来解决它,但我想知道是否有办法说服编译器我的表达式是安全的?

I really want B to be optimized out of expressions that use it when it's zero, so I need the single-line definition. I know I can just use template parameters <0, 1> to get around it, but I wonder if there's a way to just convince the compiler that my expression is safe?

推荐答案

据我所知:

 const double B = (B2 == 0 ? 0.0 : (double) B1) /
                  (B2 == 0 ? 1.0 : (double) B2);

这避免了对防止除以 0 的短路评估的依赖;在除法之前进行条件选择.

This avoids a reliance on short circuit evaluation preventing the divide by 0; having the conditional selections happen before the division.

最初的想法/也许是这样的......?(我认为 B 应该是 static constconstexpr,但我相信你可以对它进行排序...)

Original idea / Perhaps something like this...? (I think B should be static const or constexpr, but I'm sure you can sort that...)

template<int B1, int B2>
struct MyClass
{
    const double B = (double) B1 / (double) B2;
};

template <int B1>
struct MyClass<B1, 0>
{
    const double B = 0.0;
};

如果 MyClass 中有很多其他的东西你想要,并且不想复制或放入基数等等,你可以将 B 计算移动到一个使用上述专业化方法支持模板.

If there's lots of other stuff you want in MyClass and don't want to duplicate or put in a base etc., you could move the B calculation into a supporting template using the specialisation approach above.

这篇关于如何消除“除以0"模板代码错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆