2017-04-13 95 views
0
class Foo // Empty class 
{ 
}; 

template <class T> // Abstract class 
class Comparator 
{ 
public: 
    virtual ~Comparator() {} 

    virtual bool operator()(const T& e1, const T& e2) = 0; 
}; 

// Mother class that contains a map and some other methods that I did not copied here 
template <class Key, class Value, class Comparator = std::less<Key> > 
class Mother 
{ 
private: 
    std::map<Key, Value, Comparator> data_; 
}; 

// Daughter class that wants to use its own Comparator (called Nested) 
class Daughter : public Mother<Foo, Foo, typename Daugher::Nested> 
{ 
public: 
    class Nested : public Comparator<Foo> 
    { 
    bool operator()(const Foo& e1, const Foo& e2) 
    { 
     return true; // Not my real code. However, what would it mean to always return true in this kind of operation ? std::map would be pretty unusable, i guess ? 
    } 
    } 
}; 

此代碼不能編譯爲G ++不能訪問Nested,因爲我沒有訪問嵌套之前解決Daugher的模板。如果我寫Daughter<?????>::Nested,我想可能會有效。但是,我需要給Daughter自己的比較器,我無法訪問,因爲這需要我通過Daughter<?????>和遞歸訪問它。解決模板與嵌套類

我非常確定,我正在嘗試做的事情在C++中是無效的,因爲在訪問它的嵌套類之前我應該​​解決Daughter。然而,我的Nested類非常簡單,並且不需要上層的類來真正定義。

所以,我可以宣佈NestedDaughter,稱這是FooComparator或東西,但它似乎吸塵器說,這是NestedDaughter

請注意,我不希望在Foo範圍內申報operator<,因爲在我的真實情況下,它代表的是城市,我認爲對城市申報operator<並不是很乾淨。

是否有一個更清潔的選項,以便我可以聲明我的女兒類並要求它使用它自己的比較器?

回答

1

其實對我來說,一個好的解決方案就是像你說的那樣實現FooComparator,因爲如果比較器屬於Foo,所以它在Daughter之內沒有意義。如果您需要再次比較Foo而來自另一個班級,該怎麼辦?但是,也許你能有你的比較中富實現的,如果你絕對要在類中該比較器類:使用嵌套=美孚::比較

struct Foo { 
    struct Comp: Comparator<Foo> { 
    ... 
    }; 
}; 

class Daughter: public Mother<Foo, Foo, Foo::Comp> 
{ 
    ... 
}; 
+1

和可能,',''裏面Daughter'。 – Jarod42