使用算术运算符时禁止隐式转换

abr*_*ert 4 c++ arithmetic-expressions implicit-conversion

我们如何告诉 C++ 编译器在使用+和这样的算术运算符时应该避免隐式转换/,即,

size_t st_1, st_2;
int    i_1,  i_2;

auto st = st_1 + st_2; // should compile
auto i  = i_1  + i_2;  // should compile

auto error_1 = st_1 + i_2;  // should not compile
auto error_2 = i_1  + st_2; // should not compile
// ...
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 5

不幸的是,该语言指定了int将 a添加到 a时应该发生的情况size_t(请参阅其类型提升规则),因此您不能强制出现编译时错误。

但是您可以构建自己的add函数来强制参数为相同类型:

template <class Y>
Y add(const Y& arg1, const Y& arg2)
{
    return arg1 + arg2;
}
Run Code Online (Sandbox Code Playgroud)

常量引用防止任何类型转换,模板强制两个参数为相同类型。

这将始终适用于您的特定情况,因为size_t 必须是一种unsigned类型: