【发布时间】:2020-01-07 04:49:14
【问题描述】:
假设我有以下简化程序:
#include <cassert>
struct Dimensions {
Dimensions& operator=(int i) {
assert(i != 0);
return *this;
}
};
int getDim();
int main() {
Dimensions dims;
dims = getDim();//ok, just use runtime assert
dims = 0;//compile error wanted here
return 0;
}
在第一种情况 (getDim) 中,无法检查编译时,因此我们很乐意仅在运行时进行检查。
但是,当理论上看起来有可能时,是否也可以在编译时检测到(对于第二种情况,dims = 0;)? (甚至可能带有某种重载或包装器?)
【问题讨论】:
-
@george_ptr 总是会给出编译时错误,因为
i在该上下文中的常量表达式中不可用。 -
草率地说,在
dims = 0;中,0是一个运行时值。只有当您可以接受将其转换为编译时值时,您才能对其进行静态断言(例如,作为模板参数,如 StackDanny 建议的那样) -
@Bathsheba ty,这是个好主意,但是我不能在实际情况下使用它甚至不是尺寸(我只是认为这样可以更好地传达含义)
-
@darune:不确定我应该 - 我认为这太特殊了,我不会自己做,我认为运行时断言就足够了。
-
想让它与
std::is_constant_evaulated()一起工作,但它的行为很奇怪,也许其他人能够修复它godbolt。
标签: c++ c++17 compile-time static-assert