I’m attempting to create a list of objects using the variant boost.
#include <string>
#include <list>
#include <iostream>
#include <boost/variant.hpp>
using namespace std;
using namespace boost;
class CSquare;
class CRectangle {
public:
CRectangle();
};
class CSquare {
public:
CSquare();
};
int main()
{ typedef variant<CRectangle,CSquare, bool, int, string> object;
list<object> List;
List.push_back("Hello World!");
List.push_back(7);
List.push_back(true);
List.push_back(new CSquare());
List.push_back(new CRectangle ());
cout << "List Size is: " << List.size() << endl;
return 0;
}
Unfortunately, the following error is produced:
/tmp/ccxKh9lz.o: In function `main':
testing.C:(.text+0x170): undefined reference to `CSquare::CSquare()'
testing.C:(.text+0x203): undefined reference to `CRectangle::CRectangle()'
collect2: ld returned 1 exit status
I realise that everything would be fine if i used the form:
CSquare x;
CRectangle y;
List.push_back("Hello World!");
List.push_back(7);
List.push_back(true);
List.push_back(x);
List.push_back(y);
But i would like to avoid that form if at all possible, since i would like to keep my objects unnamed. This is an important requirement for my system – is there any way i can avoid using named objects?
Just need to change a few things and it works:
Specifically, you needed to define the CRectangle and CSquare constructors (that’s why you were getting a linker error) and to use
CSquare()rather thannew CSquare()etc. Also,"Hello World!"has typeconst char *, so you need to writestring("Hello World!")when passing it topush_backor it will get implicitly converted toboolhere (not what you want).