Search code examples
c++functionparsinglambdac++17

How to convert mathematical expression to lambda function in C++?


I am trying to convert string of mathematical expression to lambda function in C++17. How can I do this type of conversion with function?

std::function<void()> str2lambda(const std::string& str) {
    // Conversion
    // return lambda function
}

Example:

Input Mathematical function:
"x^2+1"

Output Lambda Function:
auto func = [](float x) -> float { return pow(x, 2) + 1; };


Solution

  • As it stands, its not going to be possible since the return type of the function is dependent on a runtime argument - the compiler cannot determine what is the return type of the function.

    On a side but slightly related note, there is a talk in cppcon23 about symbolic calculus, which relates to how symbols and expressions can be represented in C++: https://www.youtube.com/watch?v=lPfA4SFojao