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!
CodePudding user response:
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;
}
CodePudding user response:
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