C++11自动.从float转换为long
C++11 auto. convert from float to long
是否可以将foo从float转换为long(反之亦然)?
auto foo = float(1234567891234.1234);
cout << "foo: " << foo << endl;
foo = long(1234567891234.1234);
cout << "foo: " << foo << endl;
输出始终为:
foo:123457e+12foo:123457e+12
不是你写的那样。首先,
auto foo = float(1234567891234.1234);
使用自动类型推导规则来推断RHS的类型,结果为float
。一旦完成,foo
的类型就是float
,并且它是固定的(C++是静态类型的,不像Python)。下次写时
foo = long(1234567891234.1234);
foo的类型仍然是CCD_ 4并且它没有神奇地改变为CCD_。
如果你想模仿一个类型的"变化",你最多可以进行一次铸造:
cout << "foo (as long): " << static_cast<long>(foo) << endl;
或者使用额外的可变
long foo_long = foo; // again you may have a loss of precision
但是要意识到由于浮点表示可能导致的精度损失。
如果您有权访问C++17编译器,则可以使用类型安全并集std::variant<long, float>
在类型之间切换。如果没有,你可以使用像这样的简单的旧联盟
#include <iostream>
union Foo
{
float f;
long l;
};
int main()
{
Foo foo;
foo.f = float(1234567891234.1234); // we set up the float member
std::cout << "foo: " << foo.f << std::endl;
foo.l = long(1234567891234.1234); // we set up the long member
std::cout << "foo: " << foo.l << std::endl;
}
在Coliru上直播
或者,你可以使用像这样的类型擦除技术
#include <iostream>
int main()
{
void *foo; // we will store the object via this pointer
foo = new int{42};
std::cout << *(int*)foo << 'n';
operator delete(foo); // don't do delete foo, it is undefined behaviour
foo = new float{42.42};
std::cout << *(float*)foo << 'n';
operator delete(foo); // don't do delete foo, it is undefined behaviour
}
在Coliru上直播
上面代码的现代版本可以用类似std::shared_ptr
的重写
#include <iostream>
#include <memory>
int main()
{
std::shared_ptr<void> foo{new int{42}};
std::cout << *(int*)foo.get() << 'n';
foo.reset(new float{42.42});
std::cout << *(float*)foo.get() << 'n';
}
在Coliru上直播
std::unique_ptr<void>
不能工作,因为只有std::shared_ptr
实现类型擦除。
当然,如果您并不真正关心存储大小等,只需使用两个单独的变量即可。
相关文章:
- 在C++中使用GDAL可以将图像的像素坐标转换为lat,long吗
- 错误:隐式转换更改符号:'int'到'unsigned long'
- 从 long 转换C++位集构造函数的复杂性是多少?
- C++11 模板函数"implicity"将位集<N>转换为"unsigned long"
- 替换 c++ 中的 c 样式强制转换 (long&)
- 如何在<typename> <long> 不更改给定代码的情况下将自定义向量与 STL 向量相互转换?
- 为什么从无符号long-long转换为double会导致数据丢失
- 在C++中将 Java long 转换为 int64
- 将 vector<unsigned long> 转换为 char buffer[]
- 在C++中将long转换为CString
- 在c++中将unsigned long转换为char*
- c++从long转换为float的奇怪错误
- Stringstream将unsigned long转换为带逗号的格式化数字字符串
- 如何在没有sprintf()的情况下将long转换为string
- c++将Lat Long转换为BNG
- 将无符号long-long转换为wchar_t*并连接
- 如何将Lat,long转换为XY坐标系(例如UTM),然后将其映射到我的图像的像素空间
- 使用memcpy、endian将无符号long转换为std::vector
- 将 LONG 转换为函数指针
- 将long转换为wchar_t *