c++ - 传递不同的函数作为参数

标签 c++ templates

假设我有这个类:

template<class K, class Compare>
class findMax {
    K* keyArray; // Supposed to be an array of K.
    int size;

public:
      findMax (K n, Compare init); // Here I would like to initialize the array.
      ~findMax ();

      K& Find(K key, Compare cmp); // Return an elemnt in the array according to a condition.
      void printArray(Compare print); // Print the array according to a condition.

};

我想要每个 cmp当我实现构造函数时,函数会有所不同,FindprintArray .
例如:

template<class K, class Compare>
findMax<K, Compare>::findMax(int n, Compare init) {
    keyArray = new K [n];
    init(keyArray, n);
}

哪里init是我在源文件中实现的一个函数,例如:

// Init will initialize the array to 0.
void init (int* array, int n) {
    for (int i=0; i<n; i++)
        array[i] = 0;
}

不过,我希望能够将不同的函数发送到 Find例如,在两个元素之间进行比较。我无法弄清楚如何,因为当我创建一个新的 findMax 时对象,例如 findMax<int, UNKNOWN> f ,我用什么代替 UNKNOWN ?

最佳答案

试试这个-

#include <iostream>
#include <functional> 
using namespace std;

template<class K, class Compare>
class findMax {
    K* keyArray; // Supposed to be an array of K.
    int size;

public:
      findMax (K n, Compare init){init();}; // Here I would like to initialize the array.
      ~findMax (){};
    template<typename Compare1>
      K& Find(K key, Compare1 cmp){ cmp();}; // Return an elemnt in the array according to a condition.
      template<typename Compare2>
      void printArray(Compare2 print){print();}; // Print the array according to a condition.

}; 
int main() {
    findMax<int,std::function<void()>> a{5,[](){cout<<"constructor"<<endl;}};
    a.Find(5,[](){cout<<"Find"<<endl;});
    a.printArray([](){cout<<"printArray";});
    return 0;
}

关于c++ - 传递不同的函数作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41361615/

相关文章:

c++ - 使用继承的类模板避免公共(public)成员不可见和源代码膨胀/重复的更好方法?

c++ - 无法在初始化时转换匿名枚举

c++ - while循环排除条件

c++ - 是否可以将 vb.net 源代码转换为 C++?

php - 如何在PHP Plates模板引擎上显示错误

html - Magento:缩小 HTML 输出?

c++ - 使用 static_cast<datatype> 将 float 转换为字符串 c++

c++ - 在 C++ 中传递日期

javascript - 处理 WooCommerce 选定的变体自定义字段条件显示

c++ - 析构函数的部分特化