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<int>> mycoll= MyCollection<MyCollection<int>>(100);
This will indeed compile (on my MAC, using the following):
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>? 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. 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:
#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. Anyway, it works now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.