[英]Inherit dependent typedef without using struct
我有一些這樣的代碼:
#include <string>
#include <map>
typedef std::less<std::string> Comparator; // simplified
typedef std::allocator<std::pair<const std::string, int>> Allocator; // simplified
template<class T>
struct Base
{
typedef std::map<std::string, T, Comparator, Allocator> type; // VERY long declaration in the actual code
};
template<class T>
struct Container : public Base<T>::type
{
Container(Allocator a) : Base<T>::type(Comparator(), a) {}
};
int main()
{
Allocator a;
Container<int> c(a);
}
盡管聲明在我的實際代碼中更花哨 。
使用了Base結構,因此我不必多次編寫long map聲明。
我想知道是否有更好的方法可以在沒有任何Base結構的情況下從地圖繼承?
請沒有宏。 我希望以某種方式在容器類本身中隱藏typedef或類似的東西。
謝謝,
您可以依賴具有注入的類名稱的模板。 在map<...>
的專業化中,當前的專業化可以簡單地通過map
引用。 注入的類名稱也可用於派生類(和類模板)。 但是由於它是依賴的,因此需要一個合格的名稱。 它看起來比聽起來簡單,這是將別名滾動到Conatiner
:
template<class T>
struct Container : public std::map<std::string, T, Comparator, Allocator>
{
using Base = typename Container::map;
Container(Allocator a) : Base(Comparator(), a) {}
};
Container::map
是注入的類名。 別名會抓住它以便於使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.