0

我正在编写自己的、稍弱的 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

4

2 回答 2

2

发布的代码在修复了各种缺失的细节之后,例如,必要typedef的 ssize_typepointer添加默认构造函数,并进行编译和链接。鉴于缺少另一个构造函数并且基于您的错误,我很确定还有另一个构造函数看起来像这样:

template <typename S>
vector(size_type, S); // not, yet, defined

您想为此构造函数提供一个实现。

于 2013-09-15T02:49:07.097 回答
1

在我看来,您的问题是您正在重新定义 vd2。

std::vector vd2 (100, 30); // 编译正常

向量vd2 (100, 30); // 错误:未定义的引用

于 2013-09-20T14:36:42.053 回答