I
I
Ilya2019-05-24 15:03:13
OOP
Ilya, 2019-05-24 15:03:13

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;
};

And there are a bunch of classes that inherit this class by overriding the get_out method
for example:
class sinus : public function
{
sinus () :  function("sinus")
double get_out (const double x) { return sin(x);}
}

Next, I need to create a function, depending on the name of the function
. For each function, the name matches the name of the class.
function * get_function (const string name)
{
if (name == "sinus")
    retrun new sinus();
}

Is there a way to somehow avoid the huge iff stack? In order not to create your own if for each function, but to convert the string "sinus" to the sinus type?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2019-05-24
@RadioRedFox

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.

V
vanyamba-electronics, 2019-05-24
@vanyamba-electronics

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 question

Ask a Question

731 491 924 answers to any question