Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert std::string to existing function with parameters in C++

Tags:

c++

function

I've got an implemented function MyFunc(int, double, string) in my project. How can I call this function with necessary parameters having its string representation, for example

std::string str = "MyFunc(2, 3.12, \"Lemon Juice\")";

And what about the standard functions, for example, how can I call time() having std::string "time()"?


Ok, here's more detailed task. I've got a map <string, Data> Data is a class-wrapper with many childs. When I call Data.GetValue() method, it returns a std::string, depending of child class inner data. One of Data childs must return the string representation of int, another - the string representation of double, and the last one - the string representation of current date and time. Here's the problem - I don't know how to call the standard function ctime() for getting information from one of Data childs.

like image 511
Sergey Shafiev Avatar asked Oct 08 '22 12:10

Sergey Shafiev


1 Answers

You cannot in general execute code in C++ whose source is contained in a string. Probably the most compelling motivation for this is so that a C++ implementation is not required to have a C++ compiler on the machine that the code runs on, although there is more to it than just that.

You may be able to do it for specific cases. That could be:

Platform-specific, for example:

  • Wrap the source up in some boilerplate, then either call the compiler externally, link against it, or embed it in your program. This gives you a program or library.
  • Run that new program externally, or dynamically link against that library.

Input-specific, for example:

  • You could parse a function call to a particular known function, with literals as arguments, relatively easily without needing a complete C++ compiler. Get the argument values out into variables and call the function. But if you're going to do that, you could specify a more easily parsable format for the string, than one that looks like a C++ function call.

It sounds as though in your task you have a string that is one of:

  • a representation of an int
  • a representation of a double
  • a representation of a date and time.

You don't say what you want to do with this string, but whatever that is you probably need to (a) examine the string to find out which of the three it is, and then (b) do something appropriate to that format. Better, you could give the derived class the responsibility of returning the same representation no matter which of the three GetValue() returns. For example, if what you really want is seconds since 1970, add a GetSecondsSinceEpoc function, and implement it differently in each class.

like image 185
Steve Jessop Avatar answered Oct 12 '22 12:10

Steve Jessop