2014-01-15 31 views
0

功課,我們需要建立一個通用的地圖,將與給定不可修改代碼工作:收到錯誤:之前缺少模板參數「(」令牌

class startsWith { 
    char val; 
public: 
    startsWith(char v) : val(v) {}; 
    bool operator()(const std::string& str) { 
     return str.length() && char(str[0]) == val; 
    } 
}; 

void addThree(int& n) { 
    n += 3; 
} 

int main() { 
    Map<std::string, int> msi; 
    msi.insert("Alice", 5); 
    msi.insert("Bob", 8); 
    msi.insert("Charlie", 0); 

    // add To every name with B 3 points, using MapIf 
    startsWith startWithB('B'); 
    MapIf(msi, startWithB, addThree); 
} 

我寫道:

template<typename T, typename S, typename Criteria, typename Action> 
class MapIf { 
public: 
    void operator() (Map<T,S>& map, Criteria criteria, Action act) { 
     for (typename Map<T, S>::iterator iter = map.begin(); iter != map.end(); ++iter) { 
      if (criteria(((*iter).retKey()))) { 
       act(((*iter).retData())); 
      } 
     } 
    } 
}; 

,我得到的錯誤

Description Resource Path Location Type 
missing template arguments before '(' token main.cpp ‪/ex4‬ line 46 C/C++ Problem 

我n給定代碼(在MapIf(msi, startWithB, addThree);

我該如何解決? (我只能改變我代碼)

+0

它看起來像'MapIf'應該是一個函數,不是類。 – Simple

+0

順便說一句,你正在尋找的詞是「標準」 – benjymous

+0

你不能改變代碼的第一部分或第二部分? – ltjax

回答

3

看起來MapIf應該是一個函數,不是類:

template<typename T, typename S, typename Criteria, typename Action> 
void MapIf(Map<T, S>& map, Criteria criteria, Action act) 
{ 
    for (typename Map<T, S>::iterator iter = map.begin(); iter != map.end(); ++iter) { 
     if (criteria(iter->retKey())) { 
      act(iter->retData()); 
     } 
    } 
}; 
+0

tnx它的工作原理當它是一堂課時爲什麼不起作用? – user3198219

+0

@ user3198219,因爲你需要實例化一個類的對象,這意味着你需要首先像其他答案一樣編寫MapIf ()'。 – Simple