如何从实际函数中推导出std :: function参数?

scr*_*avy 3 c++ templates types c++11 std-function

上一堂课

class Foo {
 public:
  std::shared_ptr<const Bar> quux(const std::string&, std::uint32_t);
}
Run Code Online (Sandbox Code Playgroud)

我可以声明一个std::function具有相同接口的:

std::function<std::shared_ptr<const Bar>(const std::string&, std::uint32_t)> baz = ...
Run Code Online (Sandbox Code Playgroud)

有没有一种压缩该声明的方法,使得to的模板参数std::function是从该方法的声明派生的,例如:

std::function<functype(X::quux)> baz = ...
Run Code Online (Sandbox Code Playgroud)

其中functype是虚C ++操作类似decltype。有没有办法做到这一点/ 是否具有这种能力?

我确实看到该方法的签名实际上稍有不同,因为它也需要对该this对象的引用/指针。我也可以派出这样的签名。

apa*_*ara 5

是的你可以。适应如何获得可变参数模板类中的函数指针的参数类型?根据您的要求,我们得到:

template<typename T> 
struct function_traits;  

template<typename R, typename C, typename ...Args> 
struct function_traits<R(C::*)(Args...)>
{
    using type = std::function<R(Args...)>;
};

class Bar;

class Foo {
 public:
  std::shared_ptr<const Bar> quux(const std::string&, std::uint32_t);
};

int main()
{
   std::cout << std::is_same<
     std::function<std::shared_ptr<const Bar>(const std::string&, std::uint32_t)>,
     function_traits<decltype(&Foo::quux)>::type>::value << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

为了使它与常量方法一起使用,您将需要另一种专业化:

template<typename R, typename C, typename ...Args> 
struct function_traits<R(C::*)(Args...) const>
{
    using type = std::function<R(Args...)>;
};
Run Code Online (Sandbox Code Playgroud)

但是您会遇到重载方法的问题,因为要解决重载,您仍然需要指定参数。