简体   繁体   English

模板的C ++构造函数

[英]C++ Constructor for template of template

So I have a template representing say a custom collection as follows: 因此,我有一个表示自定义集合的模板,如下所示:

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

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

Now however, I want to instantiate a MyCollection of Mycollection objects, so I do this in my main program: 但是,现在,我想实例化Mycollection对象的MyCollection,因此我在主程序中执行了以下操作:

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

This will indeed compile (on my MAC, using the following): 这确实可以编译(在我的MAC上,使用以下命令):

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

The problem is that I get a linker error like this: 问题是我收到如下链接错误:

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

What exactly is this and how do I fix it? 这到底是什么,我该如何解决? It looks like it has something to do with a missing allocator for vector>? 似乎与vector>?的分配器丢失有关。 Why does this occur and how do I fix it? 为什么会发生这种情况,我该如何解决?

Your constructor takes one argument. 您的构造函数采用一个参数。 You are trying to construct the nested MyCollection without any arguments. 您正在尝试构造不带任何参数的嵌套MyCollection That is not possible. 这是不可能的。 You need to give a second constructor which takes an initializer for the inner collection. 您需要提供第二个构造函数,该构造函数使用内部集合的初始化程序。

#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));
}

Instead of the initializer you can also provide a default constructor. 除了初始化程序,您还可以提供默认构造函数。

#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);
}

Well well well, you're not going to believe this. 好吧好吧,您将不会相信这一点。 It turns out the answer had nothing to do with the command line or libraries included. 事实证明,答案与所包含的命令行或库无关。 I had a *.h file of basic data types where I had this code: 我有一个基本数据类型的* .h文件,其中包含以下代码:

#ifndef bool
#define bool unsigned char
#endif

Somehow, this messed with a prior definition of bool deep in one of the libraries, resulting in a link error that looked totally unrelated. 不知何故,这与其中一个库中的bool的先前定义混淆了,从而导致看起来完全无关的链接错误。 Anyway, it works now. 无论如何,现在就可以使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM