我有以下内容:

template<typename F, typename... Args>
void Enqueue(F&& f, Args&&... args)
{
    f(args...); // want to assign this to a variable and insert into queue/vector
}
我想将f和args(是否扩展)存储在 vector 中,以便以后可以检索并调用f(args)。 c++是否支持打包方式?

最佳答案

您可以编写这样的类:

struct Fs {

 std::vector<std::function<void()>> v;  // stores the functions and arguments
                                        // as zero argument lambdas

 template<typename F, typename... Args>
 void Enqueue(F&& f, Args&&... args)
 {
    v.push_back([=] { f(args...); });  // add function and arguments
                                       // as zero argument lambdas
                                       // that capture the function and arguments
 }

 void CallAll()
 {
   for (auto f : v)
     f();                              // calls all the functions
 }
};
然后像这样使用它:
int add(int a, int b, int c) { std::cout << "add"; return a + b + c; }
int subtract(int a, int b) { std::cout << "sub"; return a - b; }

int main(){

  Fs fs;

  fs.Enqueue(add, 1, 3, 5);
  fs.Enqueue(subtract, 5, 4);
  fs.Enqueue([](int a) { std::cout << a; }, 4);

  fs.CallAll();

}
这是demo

09-10 04:32
查看更多