小编Sid*_*hah的帖子

如何强制在C++中编译函数?

我只是在尝试使用C++.我试图编写一个小宏,以便我定义的所有函数都自动存储在一个映射中,这样我就可以在运行时查询存在的函数并运行它们.代码如下:

#include <map>
using namespace std;

typedef void (*funcPointer)();

map <char*, funcPointer> funcList;

#define Function(x) void x() { funcList[#x] = x; 
#define End }
Run Code Online (Sandbox Code Playgroud)

我被使用了funcPointer,End只是为了便于阅读和实现.现在,我可以将函数定义为

Function(helloWorld)
    cout << "Hello World";
End
Run Code Online (Sandbox Code Playgroud)

现在,要将函数名称作为列表读取并运行所有函数,我使用以下代码:

int main() {
    //helloWorld();
    for (map<char*, funcPointer>::iterator I = funcList.begin(); I != funcList.end(); I++) {
        printf(I->first);
        I->second();
    }
    getchar();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题是,如果我保持第一行main()(helloWorld();)注释,编译器不会编译该函数并跳过它进行优化,因为根据编译器,它从不使用.因此,功能列表变空.相反,如果我将函数调用一次,那么每件事情都会完美无缺,除非它打印两次"Hello World".另外,我特意写了宏,所以我不必那样做.

那么,有没有什么方法可以强制编译器编译一个函数,即使它没有被使用?

c++

1
推荐指数
1
解决办法
123
查看次数

标签 统计

c++ ×1