c++shared-ptrmake-shared

How to initialize shared_ptr not knowing its type?


I have a template function, that should get std::shared_ptr<sometype>. Inside of function I want to make a temporary variable with std::shared_ptr<sometype>, but I can't put sometype as template param because I don't know it.

#include <memory>

template<typename sometypePtr>
void foo()
{
    sometypePtr tmp_ptr = std::make_shared<sometype>();  //compilation error, because we don't know sometype
}

int main()
{
    foo<std::shared_ptr<int>>();

    return 0;
}

Is there some common way of making variable with std::shared_ptr<sometype> type?


Solution

  • Assuming that sometypePtr is a non-array std::shared_ptr, then you can use sometypePtr::element_type.

    template<typename sometypePtr>
    void foo()
    {
        sometypePtr ptr = std::make_shared<typename sometypePtr::element_type>();
    }
    

    If sometypePtr is an array std::shared_ptr, you will have to supply the extent as well as the type.