[英]C++ custom template with unordered_map
我正在嘗試創建一個自定義模板,並有這樣的代碼:
template <typename T>
struct Allocator {
typedef T value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
T *allocate(size_type n, const void *hint=0);
T *allocate_at_least(size_type n);
void deallocate(T *p, size_type n);
};
template <class T, class U>
bool operator==(const Allocator<T>&, const Allocator<U>&) {
return true;
}
int main() {
using T = long int;
std::unordered_map<
T,
T,
std::hash<T>,
std::equal_to<T>,
Allocator< std::pair<const T, T> >
> a;
}
它適用於矢量,但當我使用 unordered_map 時,它在模板內的某個地方失敗。 你能幫我弄清楚我做錯了什么嗎? 這是錯誤:
error: no matching constructor for initialization of 'std::__detail::_Hashtable_alloc<Allocator<std::__detail::_Hash_node<std::pair<const long, long>, false>>>::__buckets_alloc_type' (aka 'Allocator<std::__detail::_Hash_node_base *>')
並鏈接到代碼: https://godbolt.org/z/zje3EGjb6
PS如果我將Allocator
替換為std::allocator
一切正常。
它需要有一個默認構造函數和一個類似於復制構造函數但在非 T 類型上參數化的構造函數。 以下編譯。
template <typename T>
struct Allocator {
typedef T value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
T* allocate(size_type n, const void* hint = 0) {
return nullptr;
}
T* allocate_at_least(size_type n) {
return nullptr;
}
void deallocate(T* p, size_type n) {
}
Allocator() {} // <= this
template <class U>
Allocator(const Allocator<U>&) {} // <= and this
};
template <class T, class U>
bool operator==(const Allocator<T>&, const Allocator<U>&) {
return true;
}
int main() {
using T = long int;
std::unordered_map<
T,
T,
std::hash<T>,
std::equal_to<T>,
Allocator< std::pair<const T, T> >
> a;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.