[英]C++ template argument using function pointer
我的代碼如下:我使用函數指針創建模板類對象。 我這樣做的原因是我的比較器類Less使用一個成員函數來顯示結果。但是,如果我用operator()定義一個類,則會產生一個錯誤,即內部類無法訪問外部類的非靜態成員。 因此,我將使用一個函數來創建模板參數。
#include <iostream>
using namespace std;
template <typename Comp>
class Compare{
private:
int a[10]{1,2,3,4,5,6,7,8,9,0};
public:
// class Less{ //use inner class, can't visit the member function in OuterClass like java. so we'd use a function pointer to initialize the template
// public:
//
// };
bool Less(int v1, int v2){
return a[v1] < a[v2];
}
private:
Comp comp;
public:
void compare(int v1, int v2){
cout << comp(v1, v2);
}
};
int main()
{
Compare<&Compare::Less> c;
c.compare(1, 2);
}
但是,我得到如下錯誤:
In function 'int main()':
[Error] template argument 1 is invalid
[Error] invalid type in declaration before ';' token
[Error] request for member 'compare' in 'c', which is of non-class type 'int'
真的很想知道為什么。 謝謝!:)
使用仿函數執行此操作的簡單方法是,您只想重載operator()並將數組作為私有成員放入仿函數中,並在主函數中將此仿函數創建為實例來調用它:
#include <iostream>
using namespace std;
class Comparator{
private:
int a[10]{1,2,3,4,5,6,7,8,9,0};
public:
bool operator()(int v1, int v2) const{
return a[v1] < a[v2];
}
};
int main(){
Comparator less;
cout<<less(1,2)<<endl;
}
如果您正在編寫Dijkstra算法的比較器,則應定義一個不帶數組的簡單函數指針,因為私有成員只是重載了operator(),而不是在您定義的min_heap中傳入數組或向量,因此可以在std中找到類似的方法: :priority_queue
template<class Comparable>
Comparator<Comparable> comp;
std::priority_queue<Comparable, vector<Comparable>, Comparator<Comparable>> pq(comp,a);
希望能幫助到你。
原因:
&Compare::Less
不是類型,而模板需要類型。 它是bool (Compare::*)(int, int)
。 您可以安全地使用decltype(&Compare::Less)
。
設計:
設計似乎很脆弱,因此模板問題可能不是解決的正確問題。
此外,我僅次於@ R.Sahu所說的內容,嘗試重溫基本面。
對於算法實現,我建議您從boost.graph中汲取靈感
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.