Search code examples
c++templatesreturn-type

Retrieve element_type of std::shared_ptr when retrieving the return type of a method


I am trying to get the return type of a class method. The return type is a std::shared_ptr. From that I am trying to get the element_type. I've tried using std::result_of of as described in the answer here: https://stackoverflow.com/a/29185018/2020804

But so far I was unsuccessful. Here is my example:

class A {};
    
class B 
{
    const std::shared_ptr<A> foo() const;
};
    
const auto method = &B::foo;
using result = std::result_of<decltype(method)(B)>::type;  // const std::shared_ptr<A> &

I would now like to get the element_type of result (aka A). I've tried using decltype(result)::element_type, but I am getting an Unexpected type name 'result': expected expression error. I've also read, that std::result_of is deprecated in C++20, so I am wondering what is the correct modern solution to this problem?

Thank you very much in advance!


Solution

  • what is the correct modern solution to this problem?

    Since result_of is deprecated you should use decltype as shown below:

    const auto method = &B::foo;
    using result = decltype((B().*method)()); 
    
    //now you can get the element_type
    using ElementType = result::element_type; // typename decltype((B().*method)())::element_type;
            
    

    Demo

    Note that you can also directly get the element_type by writing:

    using ElementType = typename decltype((B().*method)())::element_type; 
    

    Demo


    but I am getting an Unexpected type name 'result': expected expression error

    The problem is that result is an alias for a type(aka type alias) and the argument of a decltype cannot be a type(or type alias).

    To solve this you can directly write result::element_type.