我有一個句法問題,
在向量類中使用以下迭代器類,
#include <memory>
#include <cstddef>
#include <iterator>
namespace ft { template <class T, class Alloc = std::allocator<T> > class vector; }
template <class T, class Alloc>
class ft::vector
{
public:
typedef T value_type;
typedef typename allocator_type::reference reference;
typedef typename allocator_type::pointer pointer;
typedef ptrdiff_t difference_type;
template <class value_type>
class ptr_iterator : public std::iterator<std::random_access_iterator_tag, value_type>
{
public:
ptr_iterator();
};
typedef ptr_iterator<value_type> iterator;
typedef ptr_iterator<const value_type> const_iterator;
};
如何解決ptr_iterator宣告之外的建構式?
我試過這種方式:
template <class T, class Alloc>
ft::vector<T, Alloc>::iterator::iterator() {}
但它產生
Vector.hpp:120:1: error: specializing member 'ft::vector<T, Alloc>::ptr_iterator<T>::iterator' requires 'template<>' syntax
ft::vector<T, Alloc>::iterator::iterator() {}
我嘗試在兩個iterator詞之后添加 <>并用 替換第二個iterator詞,ptr_iterator,但它仍然無法編譯。
在不重復函式簽名上方的兩個模板的情況下,我仍然可以使用 typedef 嗎?
或者是否有更好的迭代器宣告設計允許我同時定義迭代器和 const_iterator?
uj5u.com熱心網友回復:
對于外部定義,不幸的是,您必須重復所有嵌套模板的整個“簽名”,包括約束(如果有)。Cigien 給出了正確的形式:
template <class T, class Alloc>
template <class value_type>
ft::vector<T, Alloc>::ptr_iterator<value_type>::ptr_iterator()
{}
由于這可能是混亂且容易出錯的,您還可以將嵌套類定義為行內,或者定義為非嵌套幫助類。在 libstdc 中,前一種方法用于視圖的迭代器,但后者用于容器std::vector,例如:
typedef __gnu_cxx::__normal_iterator<pointer, vector> iterator;
typedef __gnu_cxx::__normal_iterator<const_pointer, vector>
const_iterator;
編輯:
哦,天哪,我不確定是否可以定義這樣的運算子!由于它是一個免費函式,它不需要嵌套的模板引數,我會將它放在ft命名空間中。它必須看起來像這樣:
namespace ft {
template <class T, class Alloc, class value_type>
bool operator==(
typename vector<T, Alloc>::template ptr_iterator<value_type> const& lhs,
typename vector<T, Alloc>::template ptr_iterator<value_type> const& rhs)
{ return true; }
}
但是,我已經在Compiler Explorer上嘗試過這段代碼,我的編譯器抱怨它無法推斷出向量類的引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/401080.html
