Have a simple example, with two questions related. Source code - 3 files:
parent.h:
#ifndef PARENT_H
#define PARENT_H
using namespace std;
#include <vector>
template <class CHILD_TYPE>
class PARENT
{
public:
class CHILD_DATA
{
public:
vector<CHILD_TYPE *> child_ptrs;
void dump_child_data();
};
static CHILD_DATA data;
};
template<class CHILD_TYPE>
void PARENT<CHILD_TYPE>::CHILD_DATA::dump_child_data()
{
return;
}
#endif /* PARENT_H */
child.h
#ifndef CHILD_H
#define CHILD_H
#include "parent.h"
using namespace std;
#include <string>
#include <algorithm>
#include <iostream>
#include <iterator>
class SPECIAL_CHILD : public PARENT<SPECIAL_CHILD>
{
public:
SPECIAL_CHILD (const string newname = "unnamed") : name (newname) {}
string name;
};
template<>
void PARENT<SPECIAL_CHILD>::CHILD_DATA::dump_child_data()
{
for (vector<SPECIAL_CHILD *>::iterator it = child_ptrs.begin(); it != child_ptrs.end(); it++)
{
cout << (*it)->name << endl;;
}
return;
}
#endif /* CHILD_H */
main.cpp
#include <cstdlib>
#include "parent.h"
#include "child.h"
using namespace std;
int main(int argc, char** argv) {
SPECIAL_CHILD c_a;
SPECIAL_CHILD c_b("named");
SPECIAL_CHILD c_c("named_again");
c_a.data.dump_child_data();
return 0;
}
Question 1: this example does not build:
main.cpp:12: undefined reference to `PARENT::data'
Why? Parent's member named data is public, can't I access it from a subclass object just as an own member?
Question 2: How to create in a superclass specialized template for a subclass - in my case, with template argument being a pointer to a subclass object? I definitely don't want a superclass to know anything about subclass. Should I put the specialized template definition in subclass header, as I did? Or maybe even in subclass .cpp , if such exists?
Thanks.