#include <mutex>
#include <queue>
#include <memory>
#include <string>
#include <iostream>
#include <memory>
#include <condition_variable>

#define DBG_LOG(format, ...) \
    printf("[%d:%s:%d]" format ", this:%p\n", std::this_thread::get_id(), __FUNCTION__, __LINE__, ##__VA_ARGS__, this)

struct task_base {
  virtual ~task_base() {}
  virtual void operator()() = 0;
};

template <typename F>
struct task_model : public task_base {
  F functor_;

  template <typename U> // 构造函数是函数模板
  task_model(U&& f) :
      functor_(std::forward<U>(f)) {}

  void operator()() override {
    functor_();
  }
};

class my_task {
  std::unique_ptr<task_base> ptr_;

public:
  template <typename F>
  my_task(F&& f) {
    using model_type = task_model<F>;
    ptr_ = std::make_unique<model_type>(std::forward<F>(f));
  }

  void operator()() const {
    ptr_->operator()();
  }

  // 其他部分略
};

///

// 普通函数
void foo() {
  std::cout << "type erasure 1";
}

// 重载括号运算符的类
struct foo2 {
  void operator()() {
    std::cout << "type erasure 2";
  }
};

int main() {

  my_task t1{ &foo };
  t1(); // 输出"type erasure 1"

  my_task t2{ foo2{} };
  t2(); // 输出"type erasure 2"

  // Lambda
  my_task t3{
      [](){ std::cout << "type erasure 3"; }
  };
  t3(); // 输出"type erasure 3"

  return 0;
}


备份地址: 【类型擦除示例