如何转换字符串"a>b"bool吗?
#include <iostream>
using namespace std;
float condition(float a, float b)
{
bool cond;
/*
i'd like to see a function converting string "a > b" to bool
*/
return cond
}
int main()
{
if (condition(7, 6))
{
cout << "a > b";
}
}
在Python中,我可以这样做:
def condition(a, b):
cond = f'{a} > {b}'
return cond
if eval(condition(7, 6)):
print('a > b')
在c++中,您可以利用lambda函数实现类似的功能:
#include <iostream>
using CmpFunc = bool(float, float);
CmpFunc* condition(char op) {
switch (op) {
case '>':
return [](float a, float b) { return a > b; };
case '<':
return [](float a, float b) { return a < b; };
case '=':
return [](float a, float b) { return a == b; };
default:
return [](float a, float b) { return false; };
}
}
int main() {
auto const cmp = condition('>');
if (cmp(7, 6)) {
std::cout << "a > b";
}
}