Search code examples
c++pointerscastingshared-ptr

Analogy to "cast from/to void" in std::shared_ptr


I'm using std::shared_ptr<T> for a lot of different types. Since I want to store all these different shared_ptrs in one vector, I thought having a std::vector<std::shared_ptr<void> >and cast to and from void if necessary.

I'm familiar with the following "bare pointer" usage

#include <iostream>

void print(void* void_ptr)
{
    int* int_ptr = static_cast<int*>(void_ptr);
    std::cerr << *int_ptr << std::endl;
}

int main()
{
    int* int_ptr = new int(4);
    void* void_ptr = static_cast<void*>(int_ptr);
    print(void_ptr);
    delete int_ptr;
}

This works flawlessly with g++ and afaik it's the proper way to do this if you have bare pointers. But now I want to have the same with std::shared_ptrs.

#include <iostream>
#include <memory>

void print(std::shared_ptr<void> void_ptr)
{
    std::shared_ptr<int> int_ptr = ??(void_ptr); // simple cast won't work
    std::cerr << *int_ptr << std::endl;
}

int main()
{
    std::shared_ptr<int> int_ptr = std::make_shared<int>(4);
    std::shared_ptr<void> void_ptr = ??(int_ptr); // same problem here
    print(void_ptr);
}

Is this even possible? There are a lot of different types which I have shared_ptrs to, but these types have little in common. They don't share a base class or something like that (if that's the only way, I'll do that, but it would be definitively more awesome with some sort of shared_ptr<void>).


Solution

  • std::static_pointer_cast performs this function. However, this is generally an extremely bad idea- why not boost::any or boost::variant or something? This weakly typed and weakly enforced code will only bite you in the arse.