[英]Why can't I pass a function pointer as a template parameter to a map?
我目前正在開發一個程序,我想將函數指針傳遞給自定義比較器的映射。 然而,在以下最小的、可驗證的示例中,這會產生錯誤:
#include <iostream>
#include <map>
struct CustomKey{
unsigned a;
};
bool compareCustom(const CustomKey &a, const CustomKey &b){
return a.a < b.a;
}
typedef decltype(compareCustom) CustomComparator;
int main(){
std::map<CustomKey, unsigned, CustomComparator> customMap(&compareCustom);
return 0;
}
使用 GCC 或 Clang 編譯上述代碼會產生大量無信息模板錯誤,完全以std::map
的內部實現為中心。 這個問題似乎表明傳遞函數指針類型是完全有效的。 我的代碼有什么問題?
傳遞函數指針有效,但傳遞函數無效。
typedef decltype(compareCustom) CustomComparator;
實際上使CustomComparator
類型為bool(const CustomKey&, const CustomKey&)
,這是函數本身,而不是指針。
你應該使用:
typedef decltype(compareCustom) *CustomComparator;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.