Any reason to use a run-time assert instead of compile-time assert?

﹥>﹥吖頭↗ 提交于 2019-12-04 09:11:40

There's no reason to prefer a run-time assert here. You should prefer compile-time errors over run-time errors so there's never a reason, given the option between the two, to choose a run-time assert.

However, if a static assert isn't an option (doesn't know the concept of a static assert, doesn't know how to make one and doesn't have one available, or knows how to make one but doesn't have the time to), a run-time assert is the next best thing.

With C++0x, the built-in static_assert feature should end all reason to use a run-time assert where a compile-time assert would work.

We can't tell without context. In template code, some branches might be unreachable for some instantiations. A compile-time assert would be inappropriate, as that renders the entire function illformed. An assert(<type-dependent expression>) does not.

E.g.

template <typename T> void foo(T t)
{
  if (t < 0) {
    assert(std::numeric_limits<T>::min() < 0);
    T u = t - std::numeric_limits<T>::min();
  }
}

The assert cannot be converted to a static assert, even though the run-time assert never fails.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!