如何在任何两种类型之间reinterpret_cast

How do I reinterpret_cast between any two types?

本文关键字:之间 reinterpret cast 类型 两种 任何      更新时间:2023-10-16

我想重新声明给定变量的类型,但不幸的是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) }

现场观看