1 year ago

#372545

test-img

Big Mike

Visual Studio is reporting an error, but still compiling the program and everything works as it should. Have I made a mistake in my code?

I have made a small header-only timer struct for testing the speed of functions. I made it purely out of curiosity because I am learning C++.

I have a function called "TimeTask" which has 2 overloads, The first one takes a std::function(void()) as a parameter and records how long the function takes to execute. The other one is a template function that takes a void function with any number of parameters and records its speed.

struct Timer
{
private:
    std::chrono::steady_clock::time_point begin, end;
    float Duration = 0.0f;
public:
    
    const float& getDuration() const
    {
        return Duration;
    }

    void StartTimer()
    {
        begin = std::chrono::steady_clock::now();
    }

    void StopTimer()
    {
        end = std::chrono::steady_clock::now();
        std::chrono::duration<float, std::milli> ChronoDuration = end - begin;
        Duration = ChronoDuration.count();
    }

    template<class...Args>
    void TimeTask(std::function<void(Args...)> task, Args&&...args)
    {
        StartTimer();
        task(std::forward<Args>(args)...);
        StopTimer();
    }

    void TimeTask(std::function<void()> task)
    {
        StartTimer();
        task();
        StopTimer();
    }
   

};

Quite simple really. I tested it with the following code:

void task_parameters(double j) {
    for (double i = 0; i < j * j * j * j * j; i++)
    {
    };

    std::cout << "Done\n";
}

void task_void()
{
    return;
}


int main()
{

    Timer timer;

    timer.TimeTask<double>(task_parameters,15.0);
    

    std::cout << timer.getDuration() << std::endl;

    timer.TimeTask(task_void);

    std::cout << timer.getDuration() << std::endl;

    std::cin.get();
    return 0;
}

The program compiles and runs as expected but the first time I run the TimeTask function with "double" as my parameter type, it gives me an error: E0304 no instance of overloaded function "Timer::TimeTask" matches the argument list

The program will still run, but I was wondering if I could get rid of this error? Thank you

The code appears to be correct and the behaves as expected, but I don't understand why that error is appearing.

c++

templates

overloading

variadic

0 Answers

Your Answer

Accepted video resources