在 C++ 中可能 Python `exec` 等价物

Possible Python `exec` equivalent in C++

我发现需要在终端中执行 C++ 代码。在考虑如何做到这一点时,Python 的 exec 命令是完美的。遗憾的是,我不能使用它,因为我需要一个 C++ 并行。

C++中有类似的命令吗?

据我所知,C++ 中没有 exec() 的完美等价物,因为 C++ 并非设计为以这种方式正常使用。

system() comes to mind as a near equivalent off the top of my head, although I will warn you that system() is not usually recommended for use in production code.

但是,如果链接问题中的 none 个原因困扰您,理论上您可以从 system()exit() 的组合中构造一个 exec()

void exec(const char* command, int code=0) {
    system(command);
    exit(code);
}

编辑:我可能跑题了。 There may be an exec in C++. Also, see this question.

简短的回答是否定的,c++ 不支持计算和执行任意代码。

如果您需要脚本支持,请使用脚本语言。 Lua and python are reasonably easy to integrate. chaiscript 甚至看起来很像 c++ 代码。

您可以从您的程序中调用编译器,然后 运行 生成可执行文件,但我怀疑这是否是解决您的问题的好方法。

https://docs.python.org/3/library/functions.html#exec

exec(object[, globals[, locals]])
This function supports dynamic execution of Python code.

C++ 中没有等效或相似的函数。