Mak*_*gan 0 c++ types casting type-conversion
说我想要的大小存储std::vector在int我有以下选项,据我所知:
int size = vector.size(); // Throws an implicit conversion warning
int size = (int)vector.size(); // C like typecasting is discouraged and forbidden in many code standards
int size = static_cast<int>(vector.size()); // This makes me want to gouge my eyes out (it's ugly)
Run Code Online (Sandbox Code Playgroud)
有没有其他选择可以避免上述所有问题?
我打算挑战这个问题.您不应该想要一个简短而优雅的解决方案来解决这个问题.
使用任何语言(包括C++)进行演员,基本上都是程序员相当于咒骂:你有时会这样做,因为它简单而轻松,但你不应该这样做.这意味着在某个地方,某种程度上,你的设计搞砸了.也许您需要将数组的大小传递给旧的API,但旧的API没有使用size_t.也许你设计了一段代码来使用float,但在实际实现中,你会像对待它们一样对待它们int.
无论如何,使用强制转换来修补代码中其他地方所犯的错误.您不应该想要一个简短的解决方案来解决这个问题.你应该更喜欢明确和乏味的东西,原因有两个:
所以,拥抱static_cast,dynamic_cast,const_cast,和reinterpret_cast编写代码的风格.而不是试图找到使转换更容易的方法,找到重构代码的方法,这样它们就不那么必要了.
如果你准备忽略所有这些,那么写下这样的东西:
template<typename T, typename U>
T as(U && u) {
return static_cast<T>(u);
}
int size = as<int>(values.size());
bool poly_type::operator==(base_type const& o) {
if(this == &o)
return true;
if(typeid(*this) == typeid(o)) {
return as<poly_type const&>(o).value == value;
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
这至少会减少你最终使用的打字数量.
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |