Search code examples
c++objectpointerstypesshared-ptr

Getting the Object Type from a Shared Pointer in C++


Is there a way to get the object type from a shared pointer? Suppose:

auto p = std::make_shared<std::string>("HELLO");

I want to get the string type from p i.e. something like:

p::element_type s = std::string("HELLO");

meaning: p::element_type is a std::string.

Thanks!


Solution

  • shared_ptr::element_type gives you the type held by the shared_ptr; you can access this type from p using the decltype specifier. For example:

    int main()
    {
        auto p = std::make_shared<std::string>("HELLO");
        decltype(p)::element_type t = "WORLD"; // t is a std::string
        std::cout << *p << " " << t << std::endl;
    }