Search code examples
c++c++11reinterpret-cast

How do I reinterpret_cast between any two types?


I would like to re-declare the type of a given variable, but unfortunately reinterpret_cast<> does not help here. This line:

reinterpret_cast<std::vector<double>>(std::string("Hello"));

results in the following compiler error:

invalid cast from type 'std::string {aka std::basic_string<char>}' to type 'std::vector<double>'

Is there a different, clean approach?

Notes:

  • I know that reinterpret_cast<> is not a proper conversion. I really do only want to re-declare the type here. Some code around this line will make sure it is only performed when appropriate
  • Why actually does this line above not work?
  • I am aware of this option, which I think is too messy: *reinterpret_cast(&OldType)

Edit/Some context: This line will be part of a templated function, with:

reinterpret_cast<T>(std::string())

For T == std::string this is completely fine, but unfortunately the compiler will also try to instantiate (but at runtime never use) it for T == std::vector<>. And this is C++11, so there is no static_if.


Solution

  • For T == std::string this is completely fine, but unfortunately the compiler will also try to instantiate (but at runtime never use) it for T == std::vector<>. And this is C++11, so there is no static_if.

    In C++17, as you said, you can use 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...
        }
        // ...
    }
    

    Prior to C++17, you might use overloads, potentially with tag dispatching, 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);
    
        // ...
    }