简体   繁体   English

C++ std::function<void()> 包含 shared_ptr</void()>

[英]C++ std::function<void()> contained shared_ptr

The project has some callback functions:该项目有一些回调函数:

using fn = std::function<void()>;

The callback function is a parameter of the class X's constructor:回调 function 是 class X 的构造函数的参数:

class X(fn).
X x([](){})
X.fn()

I would like to introduce another type of callback function to indicate id, so I need another type:我想介绍另一种类型的回调function来表示id,所以我需要另一种类型:

using xfn = std::function<void(int)>;

Is there a possible way to change the parameter so that it could support both types of function.有没有一种可能的方法来更改参数,以便它可以支持两种类型的 function。 The project already contains many code with the first type of function.该项目已经包含许多代码,第一种类型为 function。 They are called with X.fn() .它们用X.fn()调用。 I am trying to make class X support X.fn(100) .我正在尝试使 class X 支持X.fn(100) So people can both call X.fn() and X.fn(100) , with the same name fn.所以人们可以同时调用X.fn()X.fn(100) ,同名 fn。 (I don't want it to be a new member with a different name), just like a function with default value. (我不希望它成为具有不同名称的新成员),就像具有默认值的 function 一样。 fn() = fn(int val=100)

I want to introduce:我想介绍:

X x([](int x){})
X.fn(100)

Is it possible to change the class constructor to a more general prototype-function like是否可以将 class 构造函数更改为更通用的原型函数,例如

class X(genereal fn)

so that if class X could receive both [](){} and [](int){} .这样如果 class X 可以同时接收[](){}[](int){}

You can use templates and std::function to make it accept any type you like, as follows您可以使用模板和std::function使其接受您喜欢的任何类型,如下所示

template<typename ...T>
struct X{

    X(std::function<void(T...)>&& fn_):fn{std::move(fn_)}{}
    std::function<void(T...)> fn;
};
int main()
{
    X<int> x1{[](int x){std::cout << "\n" << x;}};
    x1.fn(3);

    X<> x2{[]( ){std::cout << "\nnon";}};
    x2.fn();
}

Live居住

Assuming you want to use the same class and allow storing and accessing both functions, you can try the following approach:假设您想使用相同的 class 并允许存储和访问这两个函数,您可以尝试以下方法:

#include <functional>
#include <iostream>

struct X
{
  struct Wrapper
  {
    Wrapper(std::function<void(int)> pfn)
      : fn(pfn)
    { }
    Wrapper(std::function<void()> pfn)
      : fn([pfn](int) { pfn(); })
      { }

    void operator()()
    {
      fn(0);
    }

    void operator()(int v)
    {
      fn(v);
    }

    std::function<void(int)> fn;
  };

  X(std::function<void()> pfn)
    : fn(pfn)
  { }
  X(std::function<void(int)> pfn)
    : fn(pfn)
  { }

  Wrapper fn;

};

int main()
{
  X x1([]() { std::cout << "no arg" << std::endl; });
  X x2([](int arg) { std::cout << "int arg = " << arg << std::endl; });
  
  x1.fn();
  x2.fn(100);

  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM