My goal is to create many objects of derived classes and store them in a std::map
with a std::string
as a key and the pointer to that object as the value. Later in the flow, I access all the keys and values and call some virtual
functions re-implemented in the derived classes.
I ended up in a situation where I had to call a template within a template.
Model.h
#include<Base.h>
class myClass {
template<typename T>
Base* createT() { new T; }
typedef std::map<std::string, Base*(*)()> map_type;
static map_type* getMap() {
if (!map) {
map = new map_type;
}
return map;
}
template<typename T>
void registerT(std::string& s) {
getMap()->insert(std::make_pair(s, createT<T>())); // problem is here 1 of 2
}
};
Model.cc
#include <Model.h>
#include <DerivedA.h>
registerT<DerivedA>("DerivedA"); // problem is here 2 of 2
registerT<DerivedB>("DerivedB");
// To be implemented getValue(). Eventual goal is this.
auto objA = getValue("DerivedA");
objA->init(); // virtual
objA->run(); // virtual
The createT
is supposed to create an object and return me the pointer. But it is not working and the compiler is throwing this error:
error: cannot call member function ‘HB::Base* myClass::createT() [with T = HB::DerivedA]’ without object
getMap()->insert(std::make_pair(s, createT<R>()));
~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~
What am I doing wrong?
())` `s` is a reference to `std::string`; it cannot be used as a template argument where a type is expected...– fabian May 25 '22 at 18:44