c++ - 如何根据 operator() 参数泛化一个类?

标签 c++ templates stl

我有一个类应该将一些参数转发给仿函数,但还做了一些额外的事情。

class SemaphoredEventRouterObserver {
   My_Semaphore m_semaphore;
   mywrapper_Function<void (*)(const Event &)> callback;
   SemaphoredEventRouterObserver(My_Semaphore semaphore, mywrapper_Function<void (*)(const Event &)> o_callback) : m_semaphore(semaphore) {
      callback = o_callback;
   }
   void operator()(const Event & event) {
      callback(event);
      semaphone.post();
   }
}    

问题是我可能必须创建许多这样的类,因为对于其他仿函数,参数各不相同,所以不是接收 const Event & event , 我可以收到 string arg , int c , Myclass abc或其他任何内容。

是否可以为此创建一个模板类?我只使用 STL 而不能使用 boost,尽管我也很想知道与 boost 相关的答案。

最佳答案

使用可变参数模板,你可以这样做:

typename <typename... Ts>
class SemaphoredRouterObserver {
   My_Semaphore m_semaphore;
   mywrapper_Function<void (*)(Ts...)> callback;
public:
   SemaphoredEventRouterObserver(My_Semaphore semaphore,
                                 mywrapper_Function<void (*)(Ts...)> o_callback)
     : m_semaphore(semaphore),
       callback(o_callback)
   {}
   void operator()(Ts... args) {
      callback(args...);
      semaphone.post();
   }
};

然后

using SemaphoredEventRouterObserver = SemaphoredRouterObserver<const Event&>;

关于c++ - 如何根据 operator() 参数泛化一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31515614/

相关文章:

c++ - kbhit() 在 MacOS 上检测按键

c++ - 为什么 `clang-format`和 `git clang-format`的结果不同

c++ - 为什么 C++03 要求模板参数有外部链接?

c++ - 详细类型说明符中的依赖于类型的嵌套名称说明符

c++ - 是否可以使用符合 C++17 的 C++14 创建迭代器?

c++ - 多线程 SQLite 崩溃

c++ - 为什么 C++ 参数作用域会影响命名空间内的函数查找?

c++ - 在模板 SFINAE 约束中使用间接级别会导致硬错误

c++ - 我是否应该将使用 push_back 的代码更改为使用 std::move?

c++ - LLDB C++调试