Last active
August 29, 2015 13:58
-
-
Save cheuerde/9930609 to your computer and use it in GitHub Desktop.
C++ derived template Class with container of pointers to base-class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
class base{ | |
public: | |
float X; | |
void getX(){ cout << endl << X << endl;} | |
void setX(float y){X=y;} | |
}; | |
template<typename T1> | |
class test_class: public base | |
{ | |
public : | |
T1 X; | |
void getX(){ cout << endl << X << endl;} | |
void setX(T1 y){X=y;} | |
}; | |
int main(){ | |
vector<base*> vec; // this is my vector of pointers to base-class | |
vec.push_back(new test_class<double>); // fill the vector with derived class | |
vec.push_back(new test_class<int>); | |
vec[0]->setX(10.3); | |
vec[1]->setX(5.78); | |
vec[0]->getX(); | |
vec[1]->getX(); // is not an integer! | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
General Problem: I need a container that stores variable types. This is impossible with std::containers like std::vector.
One workaround is to define a common base class, from which the template classes are derived and to create a vector of pointers to that base class. The vector can be filled with pointers to the derived class.
In the example the derived-class instances of X (double,int) seem still to be of type float! why?