I’m making some API and want to allow app developers to put their own callback function with any return types and any number of parameters. Below code is example I expect to work. I wonder how to define ?<?> userfunc in MyAPI.h

// MyAPI.h

using namespace API {
/**
* Executes callback function after a random time in its own thread.
* @param userfunc User defined callback function.
**/
void SetCallback(?<?> userfunc);
}
// application.cpp

#include "MyAPI.h"
#include <chrono>
#include <format>
#include <iostream>

std::string get_current_datetime() {
  const auto now = std::chrono::system_clock::now();
  return std::format("{:%d-%m-%Y %H:%M:%OS}", now);
}

bool callback_1(bool* triggered, std::string* registration_time) {
  *triggered = true;
  std::cout << "CALLBACK_1" << std::endl;
  std::cout << "registered: " << registration_time << std::endl;
  std::Cout << "triggered : " << get_current_datetime() << std::endl;
  return true;
}

int callback_2(int* triggered) {
  *triggered = 1;
  std::cout << "CALLBACK_2" << std::endl;
  return 1;
}

int main(void) {
  bool is_triggered_bool = false;
  int is_triggered_int = 0;
  std::string curr = get_current_datetime();
  API::SetCallback(std::bind(&callback_1, &is_triggered_bool, &curr));
  API::SetCallback(std::bind(&callback_2, &is_triggered_int))
  Sleep(3000);
  if (is_triggered_bool && is_triggered_int == 1) return 0;
  else return -1;
}

Any advice will appreciate

4

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *