c++ - 将可变参数函数的参数封装在类实例中

标签 c++ parameter-passing function-pointers variadic-functions

这里有一些有漏洞的代码:

template<typename... Args>
class A 
{

  typedef function_type = void(*)(Args...);

  public:
  void set_args(Args&& ... args)
  {
      // something magic manages to encapsulate
      // args in instance of A
  }
  void apply_args(function_type function)
  {
      // something magic manages to "retrieve"
      // the encapsulated args
      function(std::forward<Args>(args)...);
  }

};

这有可能吗?

最佳答案

您可以将模板参数存储在 std::tuple 的类数据成员中类型及用途 std::apply以便将存储的参数应用于提供的函数。

那么,假设您有一个像这样的 Action 类:

template <typename... Args>
class Action {
    std::tuple<Args...> args_;

public:
    Action() = default;
    Action(Args&&... args)
        : args_(std::forward<Args>(args)...)
    {}

    void args(Args&&... args) {
        args_ = std::make_tuple<Args...>(std::forward<Args>(args)...);
    }

    template <typename F>
    void apply(F&& fun) {
        std::apply(std::forward<F&&>(fun), args_);
    }
};

通过构造函数 Action action(1, 2, 3); 或通过单独的函数 action.set(3, 2, 1); 设置参数。

那么你的主函数可以如下所示:

int main() {
    Action action(1, 2);

    action.apply([](int a, int b) {
        std::cout << "a + b = " << (a + b) << std::endl;
    });

    return 0;
}

检查live example

关于c++ - 将可变参数函数的参数封装在类实例中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60216917/

相关文章:

c++ - 获取上次激活窗口的窗口句柄

c++ - 函数模板的模板参数名是否可以在函数参数列表中多次使用?

c# - 如何获得指向 C 函数的指针?

c++ - 使用字符串作为缓冲容器

c++ - Delphi链接器和C++链接器的区别

c++ - C++中的任意类型转换

javascript - 在函数外使用变量

powershell - 如何抑制用户在没有参数参数的情况下调用我的 powershell 脚本时发生的错误

c++ - 解释这个 C++ 函数如何返回一个数组

c++ - 在调用传递给模板函数的函数时调用指向成员函数的指针