gpt4 book ai didi

带断言的 C++ static_cast

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:20:05 28 4
gpt4 key购买 nike

不幸的是,我必须在调用第 3 方库时执行缩小转换。我不想在我的发布版本中增加开销,所以将使用 static_cast。但是,它是一个数组索引,因此如果它最终为负数,可能会带来一些乐趣。是否有某种方法可以仅在 Debug模式下创建安全转换,以检查值以确保转换期间没有丢失?我能想到的唯一方法是使用宏,但我不想这样做。

例如,在使用 MSVC 的发布和 Debug模式下:

int main() {
long long ll = std::numeric_limits<long>::max();
++ll;
std::cout << ll << "\n";
long l = static_cast<long>(ll);
std::cout << l << "\n";
}

输出结果:

2147483648
-2147483648

使用宏:

template<class to, class from>
to checked_static_cast(const from& from_value) {
to to_value = static_cast<to>(from_value);
if (static_cast<from>(to_value) != from_value)
throw std::runtime_error("Naughty cast");
return to_value;
}

#ifdef _DEBUG
#define debug_checked_static_cast(to, val) checked_static_cast<to>(val)
#else
#define debug_checked_static_cast(to, val) static_cast<to>(val)
#endif

int main() {
try {
long long ll = std::numeric_limits<long>::max();
++ll;
std::cout << ll << "\n";
long l = debug_checked_static_cast(long, ll);
std::cout << l << "\n";
} catch (const std::exception& e) {
std::cerr << "ERROR: " << e.what() << "\n";
}
}

在 Release模式下产生相同的输出,但在 Debug模式下产生以下结果:

2147483648
ERROR: Naughty cast

有更好的选择吗?

注意:我忽略了我们可能会从一个足够大的阵列中享受到的娱乐,从而导致这个问题,也许这只是过于偏执,但我想这个概念可能有我的特定要求以外的应用。

最佳答案

不需要宏,您可以简单地在函数体内使用预处理器条件:

template<class to, class from>
inline to debug_checked_static_cast(const from& from_value) {
to to_value{static_cast<to>(from_value)};
#if _DEBUG
from round_trip{to_value};
if (round_trip != from_value)
throw std::runtime_error("Naughty cast");
#endif
return to_value;
}

template<class to, class from>
inline to debug_checked_coercion(const from& from_value) {
to to_value{from_value};
#if _DEBUG
from round_trip{to_value};
if (round_trip != from_value)
throw std::runtime_error("Naughty cast");
#endif
return to_value;
}

然后使用

long l = debug_checked_coercion<long>(ll);

请注意,我已将 static_cast 的使用减到最少,因为缩小数字转换不需要它。

关于带断言的 C++ static_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23830292/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com