2016-07-25 118 views
1

我正在嘗試編寫一個定義std::map的類。映射的比較器必須是一個函數指針。函數指針可以作爲類的構造函數中的參數傳遞給類。即使定義了變量,變量也沒有類類型

下面是我寫的代碼:

#include <iostream> 
#include <map> 
#include <string> 
#include <functional> 

typedef std::function<bool(std::string x, std::string y)> StrComparatorFn; 

bool FnComparator(std::string x, std::string y) { 
    return strtoul(x.c_str(), NULL, 0) < strtoul(y.c_str(), NULL, 0); 
} 

class MyClass { 
public: 
    MyClass(StrComparatorFn fptr):fn_ptr(fptr){}; 

    void Insert() { 
    my_map.insert(std::pair<std::string, std::string>("1", "one")); 
    my_map.insert(std::pair<std::string, std::string>("2", "two")); 
    my_map.insert(std::pair<std::string, std::string>("10", "ten")); 
    } 

    void Display() { 
    for (auto& it : my_map) { 
     std::cout << it.first.c_str() << "\t => " << it.second.c_str() << "\n"; 
    } 
    } 
private: 
    StrComparatorFn fn_ptr; 
    std::map<std::string, std::string, StrComparatorFn> my_map(StrComparatorFn(fn_ptr)); 
}; 

int main() { 
    MyClass c1(&FnComparator); 
    c1.Insert(); 
    c1.Display(); 
} 

我得到一個編譯錯誤在Insert

error: '((MyClass*)this)->MyClass::my_map' does not have class type 
my_map.insert(std::pair<std::string, std::string>("1", "one")); 

任何解決這個問題?

回答

2

那行

std::map<std::string, std::string, StrComparatorFn> my_map(StrComparatorFn(fn_ptr)); 

有一個被稱爲最令人頭痛的解析問題。基本上,一切可以解釋爲一個功能,將是:

Foo f(); //f is a function! Not a variable 

在你的情況,my_map被解析爲沒有定義聲明的功能。使用大括號代替弧形大括號可以解決問題,因爲列表初始化永遠不能解釋爲函數:

std::map<std::string, std::string, StrComparatorFn> my_map{ StrComparatorFn(fn_ptr) }; 
+0

非常感謝。奇蹟般有效!! – VinK