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

관련 문제