Search code examples
c++c++11compile-timedecltype

Storing return type and arguments type of a method


Is it possible to determine and store the return type of SomeMethod using decltype (if it is the best way to do it, otherwise what is the best way to do it) at compile time ?

Is it also possible to use the same tool to store a type list of the arguments of SomeMethod ?

This idea behind that is to make them easily accessible from outside the class using getters.

class SomeClass
{
public:
    typedef [???] ProcRetType;
    typedef [???] ProcArgTypeList;

public:
    SomeClass() { }
    ~SomeClass() noexcept { }

    SomeType SomeMethod( SomeType1 arg1, SomeType2 arg2 ) { }

    // Data members
private:
};

Solution

  • For the return type, you can just use decltype:

    typedef decltype(SomeMethod(std::declval<SomeType1>(), std::declval<SomeType2>())) ProcRetType;
    

    For the parameters, you'll need a helper trait. That can also be used for the return type, like this:

    template <class Func>
    struct Helper;
    
    template <class T, class R, class... Arg>
    struct Helper<R (T::*)(Arg...)>
    {
      typedef std::tuple<Arg...> ArgTypes;
      typedef R ReturnType;
    };
    

    And then use it like this:

    typedef Helper<decltype(&SomeClass::SomeMethod)>::ReturnType ProcRetType;
    typedef Helper<decltype(&SomeClass::SomeMethod)>::ArgTypes ProcArgTypeList;
    

    I'm using std::tuple to represent the type list - other representations are also possible, such as Boost.MPL.

    You might need to provide a few other partial specialisations of Helper to account for const functions (and possibly volatile and old-style variadic functions as well, if that applies to you).