我正在编写自己的、稍弱的 STL 版本(目前它不支持分配器)。
这里最重要的一点是:
template <typename T>
class vector
{
public:
typedef T value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef random_access_iterator<T> iterator;
typedef random_access_iterator<const T> const_iterator;
typedef unative_t size_type;
typedef native_t difference_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
vector(const size_type n = 0) : vector<T>(n, T()) { }
vector(const size_type n, const T& val) : m_capacity(n == 0 ? 100 : n * 2),
m_size(n), m_data(new T[m_capacity])
{
for (decltype(m_size) i = 0; i < m_size; ++i)
m_data[i] = val;
}
// fancy declarations go here...
private:
size_type m_capacity; // Where size_type is the unsigned word size of the CPU
size_type m_size; // for my computer, this is the equivalent of uint64_t.
pointer m_data; // At present, pointer is T*
}
现在我在 Mint 15 上,编译:
g++ -std=c++11 -Wall -Werror # gcc-4.8.1
实现文件是:
#include "structures/vector.hpp"
#include <vector>
int main()
{
vector<int> vi; // compiles okay
vector<float> vf(10); // compiles okay
vector<double> vd1(100, 30.0); // compiles okay
std::vector<double> vd2(100, 30); // compiles okay
vector<double> vd2(100, 30); // error: undefined reference to
// vector<double>::vector<int>(int, int)
return 0;
}
我试过从 GCC 4.8.1 中筛选 std::vector ,但结果很少。我能看到的唯一真正的区别是我没有使用分配器,但这不应该对类的实例化产生影响!
虽然我只给出了相关信息,但这就是我到目前为止所实施的全部。在编写模板类时,我倾向于利用惰性实例化规则并在编写时测试所有内容(速度较慢,但至少我知道一切正常)。
非常感谢任何帮助。
干杯,
cjdb01