如何在任何两种类型之间reinterpret_cast
How do I reinterpret_cast between any two types?
我想重新声明给定变量的类型,但不幸的是reinterpret_cast<>在这里没有帮助。这一行:
reinterpret_cast<std::vector<double>>(std::string("Hello"));
导致以下编译器错误:
invalid cast from type 'std::string {aka std::basic_string<char>}' to type 'std::vector<double>'
有没有不同的、干净的方法?
笔记:
- 我知道reinterpret_cast<>不是一个适当的转换。我真的只想在这里重新声明类型。此行周围的一些代码将确保仅在适当时才执行
- 为什么上面的这一行实际上不起作用?
- 我知道这个选项,我认为它太混乱了:*reinterpret_cast(&OldType(
编辑/一些上下文:此行将是模板化函数的一部分,具有:
reinterpret_cast<T>(std::string())
对于 T == std::string,这是完全没问题的,但不幸的是,编译器也会尝试实例化(但在运行时从不使用(它用于 T == std::vector<>。这是C++11,所以没有static_if。
你不能
,这样做是没有意义的,编译器告诉你的。
reinterpret_cast
不能将类型破解为完全不相关的类型。
即使确实如此,例如您在最后一个项目符号中展示的指针黑客行为,该语言的规则也禁止您使用经过这种强制转换的对象。
干脆不要这样做,因为你不能。
如果您尝试从字符串 (?( 构造双精度向量,请完全按照业务需求禁止的方式编写适当的代码以从字符串生成双精度
向量。类型系统可以帮助您。让它吧。
对于 T == std::string,这是完全没问题的,但不幸的是,编译器也会尝试实例化(但在运行时从不使用(它用于 T == std::vector<>。这是C++11,所以没有static_if。
正如您所说,在 C++17 中,您可以使用if constexpr
:
template <typename T>
void foo(const T& value)
{
bar(value);
if constexpr (std::is_same<std::string, T>::value) {
// Specific code for string
} else constexpr (std::is_same<std::vector<int>, T>::value) {
// specific code for vector...
}
// ...
}
在 C++17 之前,您可以使用重载,可能使用标记调度 SFINAE。
void foo_specific(const std::string& s)
{
// Specific code for string
}
void foo_specific(const std::vector<T>& v)
{
// Specific code for vector
}
template <typename T, std::enable_if_t<std::is_integral<T>::value>, int> = 0>
void foo_specific(const T& n)
{
// Specific code for integral
}
// ...
template <typename T>
void foo(const T& value)
{
bar(value);
foo_specific(value);
// ...
}
你想要从字符串文本构造一个容器。
使用不同的构造函数重载,例如
template< class InputIt >
basic_string( InputIt first, InputIt last, const Allocator& alloc = Allocator());
哪个兼容
template< class InputIt >
vector( InputIt first, InputIt last, const Allocator& alloc = Allocator() );
因此
char hello[] = "Hello";
T{ std::begin(hello), std::end(hello) }
现场观看
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- 在cuda线程之间共享大量常量数据
- 在c代码之间共享数据的最佳方式
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 大小相等但成员数量不同的结构之间的性能差异
- 类与私有变量的其他类之间的线程安全性
- 如何在cpp文件之间切换窗口?在Qt中
- 线程之间的布尔停止信号
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在 const 函数中通过引用和指针返回之间的区别
- 我想知道长双倍和双倍之间的区别
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 构造函数和转换运算符之间的重载解析
- C++20 中的严格别名规则是否允许标准 c++ unicode 字符和下划线类型之间"reinterpret