Maths 4Us
Maths 4Us

Reputation: 35

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!

Upvotes: 2

Views: 2150

Answers (2)

aradarbel10
aradarbel10

Reputation: 473

as you've probably seen, per cppreference, std::shared_ptr has a type alias member_type = std::remove_extent_t<T>.

to access it, you can do something like

auto p = std::make_shared<std::string>("hello");
decltype(p)::element_type s = std::string{"heya"};

the type alias is associated to the class itself, not the specific member! godbolt

Upvotes: 1

Jonathan Potter
Jonathan Potter

Reputation: 37122

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;
}

Upvotes: 5

Related Questions