Alex
Alex

Reputation: 1

Can I use a std::string variable as an argument to an operator?

For example, if I have:

#include <iostream>

using namespace std;

int main()
{
    int b = 1;
    int c = 2;
    string a = "(b + c)";
    
    cout << (4 * a) << "\n";

    return 0;
}

Is it possible to have string a interpreted literally as if the code had said cout << (4 * (b + c)) << "\n";?

Upvotes: 0

Views: 111

Answers (2)

eerorika
eerorika

Reputation: 238361

No. C++ is not (designed to be) an interpreted language.

Although it's theoretically possible to override operators for different types, it's very non-recommended to override operators that don't involve your own types. Defining an operator overload for std::string from the standard library may break in future. It's just a bad idea.

But, let's say you used a custom type. You could write a program that interprets the text string as a arithmetic expression. The core of such program would be a parser. It would be certainly possible, but the standard library doesn't provide such parser for you.

Furthermore, such parser wouldn't be able to make connection between the "b" in the text, and the variable b. At the point when the program is running, it has no knowledge of variable names that had been used to compile the program. You would have to specify such information using some form of data structure.

P.S. You forgot to include the header that defines std::string.

Upvotes: 8

Red.Wave
Red.Wave

Reputation: 4225

#include<string>
///...
auto a=std::to_string(b+c);
std::cout<<4*std::stoi(a)<<std::endl;

You can just use std::string and std::stoi.

Upvotes: -5

Related Questions