C++ 如何将字符串传递给宏函数
我正在使用lib将一些资源文件嵌入到可执行文件中 可以通过宏功能访问资源 我要嵌入的资源: resource/my_resource1.xml resource/my_resource2.xml resource/type1/my_resource3.xml resource/type1/my_resource4.xml resource/type2/my_resource3.xml resource/type2/my_resource4.xml ... 加载公共资源很容易:C++ 如何将字符串传递给宏函数,c++,C++,我正在使用lib将一些资源文件嵌入到可执行文件中 可以通过宏功能访问资源 我要嵌入的资源: resource/my_resource1.xml resource/my_resource2.xml resource/type1/my_resource3.xml resource/type1/my_resource4.xml resource/type2/my_resource3.xml resource/type2/my_resource4.xml ... 加载公共资源很容易: Resource
Resource res1 = LOAD_RESOURCE(resource_my_resource1_xml);
Resource res2 = LOAD_RESOURCE(resource_my_resource2_xml);
我的问题是,我只知道运行时的类型,所以如何加载资源3和资源4
我目前的解决方案是通过一个开关箱:
Resource res3, res4;
switch (type)
{
default:
case 1:
res3 = LOAD_RESOURCE(resource_type1_my_resource3_xml);
res4 = LOAD_RESOURCE(resource_type1_my_resource4_xml);
break;
case 2:
res3 = LOAD_RESOURCE(resource_type2_my_resource3_xml);
res4 = LOAD_RESOURCE(resource_type2_my_resource4_xml);
break;
}
然而,当我有N个类型,每个类型有N个资源时,这既不是很有效也不是很漂亮
有更好的选择吗?我是否可以将字符串作为参数传递给宏函数?比如加载资源类型+类型+\u我的资源xml
我是否可以将字符串作为参数传递给宏函数
不,你不能。在编译器实际看到代码之前,宏由预处理器展开。简言之,宏是关于文本重放的,而不是更多
我的问题是,我只知道运行时的类型,所以如何加载资源3和资源4
我不知道库,但资源只是指向数据的指针和数据长度。加载资源只不过是为您提供一个句柄。因此,我会在程序启动时加载所有资源,然后根据需要在运行时访问它们
为了便于示例,假设这是库代码
#define LOAD_RESOURCE(path) ([](){ return Resource{}; })()
struct Resource {};
那么我可能会用这个:
#include <map>
#include <utility>
using key = std::pair<int,int>;
std::map<key,Resource> load_all_resources(){
return {
{ {1,1} , LOAD_RESOURCE(resource_type1_my_resource1_xml) },
{ {1,2} , LOAD_RESOURCE(resource_type1_my_resource2_xml) }
};
}
int main (){
auto resources = load_all_resources();
auto type = 1;
auto res1 = resources[{type,1}];
}
以致
std::map<key,Resource> load_all_resources(){
return {
MY_LOAD_RESOURCE(1,1),
MY_LOAD_RESOURCE(1,2),
};
}
展开到与上面相同的位置 预处理器在计算任何代码之前运行。
std::map<key,Resource> load_all_resources(){
return {
MY_LOAD_RESOURCE(1,1),
MY_LOAD_RESOURCE(1,2),
};
}