mercredi 28 octobre 2020

C++17 Template argument deduction failed

I wanted to simulate timer which would call a function (callback) periodically for that i wrote following snippet (naive though) wherein, Argument deduction is failing at line Timer/<int, int, float>/.. in main function. I am compiling this code with c++17 std. How I can fix this? or those arguments necessary? Any help in this regard is appreciated.

#include <iostream>
#include <functional>
#include <chrono>
#include <thread>

using namespace std::chrono_literals;

template<typename ...Args>
class Timer
{
public:
  Timer(std::function<void(Args...)> func, Args&&... args, std::chrono::milliseconds step)
    : m_callback{ func },
      m_args{ std::forward<Args>(args)... },
      m_stop{ false },
      m_time{ step }
  {
    this->start();
  }

  ~Timer() { stop(); puts(__func__); }

  void stop() { m_stop = true; }

private:
  void start()
  {
    auto callback = [this]() {
      while (!this->m_stop)
      {
        std::apply(m_callback, this->m_args);
        std::this_thread::sleep_for(this->m_time);
      }
    };

    m_executer = std::thread{ callback };
    m_executer.detach();
  }

private:
  std::function<void(Args...)> m_callback;
  std::thread m_executer;
  std::tuple<Args...> m_args;
  std::chrono::milliseconds m_time;
  bool m_stop;
};

int main()
{
  // Create a timer
  auto timer = Timer/*<int, int, float>*/([](int a, int b, float c) { std::cout << a + b + c << '\n'; }, 15, 17, 12.0f, 500ms);

  // Stop timer after 10s
  bool running{ true };
  std::thread{ [&]() { std::this_thread::sleep_for(10s); timer.stop(); running = false; } }.join();
  
  // Simulate long running process
  //size_t n{ 0 };
  //while (running) n += 1;

  return 0;
}

Aucun commentaire:

Enregistrer un commentaire