重载成员函数的decltype

Mar*_*rry 10 c++ templates template-specialization variadic-templates c++11

我有这个代码:

struct Foo 
{
    int print(int a, double b);
    int print(int a);
    void print();
    void print(int a, int b, int c);

    void other();
};
Run Code Online (Sandbox Code Playgroud)

我可以打电话

decltype(&Foo::other)
Run Code Online (Sandbox Code Playgroud)

但是打电话

decltype(&Foo::print)
Run Code Online (Sandbox Code Playgroud)

以错误告终,这对我来说很清楚.

但是我怎样才能更加"密切"地指定print我要解决的四种方法中的哪一种decltype呢?

我想进一步使用它

template <class MT>
struct method_info;

template <class T, class Res, class... Args>
struct method_info<Res(T::*)(Args...)>
{
    typedef std::tuple<Args&&...> args_tuple;
    typedef T ClassType;
    typedef Res RetVal; 
};



template <class MethodType>
void func() {
   typedef method_info<MethodType> MethodInfo;
   .....
}

func<decltype(&Foo::other)>();
....
Run Code Online (Sandbox Code Playgroud)

dav*_*igh 6

据我所知,更"密切",意味着你要指定的函数参数print.也就是说,例如,您选择int, int,然后返回结果类型Foo{}.print(int{},int{}),然后从所有可用信息构造一个函数指针.

这是一个别名模板,它以一般方式为您执行此操作:

template<typename ... Args>
using ptr_to_print_type = decltype(std::declval<Foo>().print(std::declval<Args>() ...)) (Foo::*)(Args ...);
Run Code Online (Sandbox Code Playgroud)

你也可以用std::result_of而不是std::declval东西,但我更喜欢后者.

你可以使用上面的

func<ptr_to_print_type<int,int> >();
Run Code Online (Sandbox Code Playgroud)

编辑:正如@JavaLover所要求的那样,对于如此糟糕的C++狗屎而言,这似乎是一个不合适的名字:-),这里与上面的相同std::result_of(现在未经测试和错误):

//------ does not compile for overloaded functions --------
template<typename ... Args>
using ptr_to_print_type = std::result_of_t<decltype(&Foo::print)(Foo, Args ...)> (Foo::*)(Args ...)
//------ does not compile for overloaded functions --------
Run Code Online (Sandbox Code Playgroud)

您可以进一步抽象Foo而不是print(除非您使用宏).