Answer the question
In order to leave comments, you need to log in
Can a string be converted to a type in C++?
There is a parent class function
class function
{
public:
function (const string &Name) name(Name) {}
virtual double get_out (const double x) const =0;
string name;
};
class sinus : public function
{
sinus () : function("sinus")
double get_out (const double x) { return sin(x);}
}
function * get_function (const string name)
{
if (name == "sinus")
retrun new sinus();
}
Answer the question
In order to leave comments, you need to log in
There is no such way in C++. But you can create a string map for function factories, register all functions in it, and get it by name.
template <class _T>
class FunctionT : public function
{
public:
static const char m_name[];
function* get_function(const string& name) {
if (name == m_name)
return new _T;
return nullptr;
}
};
using namespace std;
vector<function*> functions;
functions.push_back( new FunctionT<sinus> );
functions.push_back( new FunctionT<cosinus> );
functions.push_back( new Function<tangens> );
for(vector<function*>::iterator it = functions.begin(); it != functions.end(); ++it) {
function* f = (*it)->get_function("sinus");
if ( f != nullptr )
f->get_out();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question