2017-08-31 72 views
0

的模板,所以我有代表说,自定义集合如下模板:C++构造模板

template <typename T> class MyCollection { 
    private: 
     std::vector<T> v; 

    public: 
     MyCollection(int n) { 
      v.resize(n); 
     } 
    etc 
} 

但是现在,我要实例MyCollection的对象MyCollection的,所以我做这在我的主程序:

MyCollection<MyCollection<int>> mycoll= MyCollection<MyCollection<int>>(100); 

这确实会编译(我的MAC,使用以下):

clang++ -std=c++11 -stdlib=libc++ test.cpp 

问题是我得到这样一个链接器错误:

Undefined symbols for architecture x86_64: 
"std::__1::__vector_base_common<(unsigned char)1>::__throw_length_error() const", referenced from: 
    std::__1::vector<MyCollection<int>, std::__1::allocator<MyCollection<int> > >::allocate(unsigned long) in test-891fb4.o 

这究竟是什么,我该如何解决它?它看起来像一个关于vector>的分配器丢失了吗?为什么会发生这种情况,我该如何解决?

+0

默认的C++运行时是GNU实现,并在使用libC++编译时混淆链接器。 –

+0

那么我该如何解决这个问题? – Marc

+0

你试过了吗?clang ++ -std = C++ 11 -stdlib = libC++ test.cpp -lsupC++'? libsupC++定义了异常 – Praetorian

回答

1

你的构造函数有一个参数。您正尝试构建嵌套的MyCollection而没有任何参数。这是不可能的。你需要给第二个构造函数,它为内部集合提供一个初始化器。

#include <vector> 

template <typename T> 
class MyCollection 
{ 
private: 
    std::vector<T> v; 

public: 
    explicit MyCollection(int n) : v(n) {} 
    explicit MyCollection(int n,T const& init) : v(n,init) {} 
}; 

int main() 
{ 
    MyCollection<MyCollection<int>> mycoll(100,MyCollection<int>(1)); 
} 

除了初始值设定项,您还可以提供一个默认构造函数。

#include <vector> 

template <typename T> 
class MyCollection 
{ 
private: 
    std::vector<T> v; 

public: 
    MyCollection() : v(0) {} 
    explicit MyCollection(int n) : v(n) {} 
}; 

int main() 
{ 
    MyCollection<MyCollection<int>> mycoll(100); 
} 
+0

对不起,我仍然得到相同的链接错误 – Marc

+0

@Marc也许你需要明确地链接LibC++'clang ++ -stdlib = libC++ test.cpp -lC++' –

+0

我也试过,没有运气 – Marc

0

好吧,你不会相信这一点。事实证明,答案与包含的命令行或库无关。我有基本的数据类型的* .h文件,其中我有这个代码:

#ifndef bool 
#define bool unsigned char 
#endif 

不知何故,这个混乱与布尔深的一个预先定义的库之一,导致看起来风马牛不相及的链接错误。无论如何,它现在起作用。

+1

你为什么要在你的代码中加入类似的东西?不要混淆基本类型!如果你需要一些破损的API,最好使用'使用bool_t =无符号字符',并在每个地方使用'bool_t'而不是'bool'。 –