2016-07-25 95 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