【问题标题】:A function that take another function as parameter, "No matching function error" C++将另一个函数作为参数的函数,“无匹配函数错误”C++
【发布时间】:2021-04-23 08:34:22
【问题描述】:

我正在编写一系列排序算法并计算每个算法的执行时间。

#include <iostream>
#include <vector>
#include <chrono>
#include <utility>


#include "sort.h"


template<class T>
void timeTaken(void (*f)(std::vector<T>& nums))
{
    auto t1 = std::chrono::high_resolution_clock::now();
    f();
    auto t2 = std::chrono::high_resolution_clock::now();

    double duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();

    std::cout << duration << " microseconds";
    
   // return duration;
}



template<typename T>
void display(std::vector<T>& nums)
{
    for(int x : nums) std::cout << x << "  ";
    std::cout << "\n\t ---------------------------------- \n";
}

void displayTesting()
{
    std::cout << "testing .... \n";
}

int main()
{
   
    std::vector<int> A {4,5,2,7,1,10,15};
    
    std::cout << "ORIGNAL ARRAY: ";
    
    display(A);
    
    

    bubbleSort(A);
    timeTaken(&display);        //ERROR: No matching function for call "time Taken"
    std::cout << "BUBBLE SORT: ";
    display(A);
              
  
    


    
    
    std::cout << "\n";
    return 0;
}

当我尝试将 displayTesting() 作为 timeTaken() 的参数时,它工作正常(当然我在 (*f) 之后删除了参数)。所以我认为问题基本上是我如何将某个函数的参数带入 timeTaken() 函数。

【问题讨论】:

    标签: c++ function templates parameters


    【解决方案1】:

    display 是一个模板; timeTaken(&amp;display);中不能推导出模板参数T

    您可以通过static_cast指定实例化,

    timeTaken(static_cast<void (*)(std::vector<int>&)>(&display));
    

    或者

    timeTaken(&display<int>);
    

    或显式指定模板参数。

    timeTaken<int>(&display);
    

    其他问题:

    1. 没有bubbleSort
    2. f(); 正在尝试不带参数地调用 f,但它应该接受 std::vector&lt;T&gt;&amp;

    【讨论】:

    • 解决这个问题,timeTaken() 内部仍然存在问题 - f 是一个指向以 vector 为参数的函数的指针,但 timeTaken() 正在尝试调用 @ 987654337@ 不传递 vector 给它。
    • 所以当 f() 没有参数时,timeTaken() 发生错误。 f() 不会接受任何向量& 参数
    • @FloydVu0531 也许你想要这个? wandbox.org/permlink/1hEva3Mc6ihJtDsp
    • bubbleSort 只是我试图放入 timeTaken() 中的一个函数
    猜你喜欢
    • 1970-01-01
    • 2016-09-23
    • 2022-01-11
    • 2013-07-10
    • 2017-03-29
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    相关资源
    最近更新 更多