存储方法的返回类型和参数类型

Ath*_*ase 3 c++ decltype compile-time c++11

是否有可能确定和存储的返回类型SomeMethod使用decltype(如果是做的最好办法,否则什么是做到这一点的最好办法)在编译时?

是否也可以使用相同的工具来存储参数的类型列表SomeMethod

这背后的想法是使用getter从类外部轻松访问它们.

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

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

    SomeType SomeMethod( SomeType1 arg1, SomeType2 arg2 ) { }

    // Data members
private:
};
Run Code Online (Sandbox Code Playgroud)

Rei*_*ica 5

对于返回类型,您可以使用decltype:

typedef decltype(SomeMethod(std::declval<SomeType1>(), std::declval<SomeType2>())) ProcRetType;
Run Code Online (Sandbox Code Playgroud)

对于参数,您将需要一个辅助特征.这也可以用于返回类型,如下所示:

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;
};
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

typedef Helper<decltype(&SomeClass::SomeMethod)>::ReturnType ProcRetType;
typedef Helper<decltype(&SomeClass::SomeMethod)>::ArgTypes ProcArgTypeList;
Run Code Online (Sandbox Code Playgroud)

std::tuple用来表示类型列表 - 其他表示也是可能的,例如Boost.MPL.

您可能需要提供一些其他部分特化Helper以考虑const函数(volatile如果适用于您,可能还有旧式可变参数函数).

  • `Helper <&SomeClass :: SomeMethod> :: ReturnType`看起来不对.应该是`Helper <decltype(&SomeClass :: SomeMethod)> :: ReturnType`. (2认同)