我需要两个系统来映射类型 - 源数据字段,可以是数字,字符或字符串,都存储为字符串对象; 目标系统需要为每个数据字段的基础类型使用不同的数据类型,我需要动态地执行此映射.
基本上,对于每个数据字段,我都有实际的字段字符串's'和底层数据的类型'type',我试图根据'type'转换为'dest'类型.我一直在尝试使用模板和模板常量来破解可以做到这一点的东西,没有运气.
我目前的尝试是以下,但由于冲突的返回类型,这不会编译:
template<class CLASSTYPE, int CLASSID>
CLASSTYPE returnDifferentTypes()
{
using namespace std;
if (CLASSID == 1) // 1 = "string"
return std::string("returned string");
if (CLASSID == 2) // 2 = int
return 123;
if (CLASSID == 3) // 3 = double
return 123.123;
}
Run Code Online (Sandbox Code Playgroud)
所以我一直在打电话
string mapped = returnDifferentTypes<string, 1>()
or
int mapped = returnDifferentTypes<int, 2>()
Run Code Online (Sandbox Code Playgroud)
任何人都可以推荐更聪明的清洁方式吗?理想情况下,我试图返回适当的返回类型,只有一个表示要映射到的类型的字符串.提前致谢.
对于您的情况,CLASSID
是一个冗余参数; 所以省略它.
您可以简单地为不同的数据类型专门化该方法returnDifferentTypes
以获得更清洁的方式.
template<class CLASSTYPE>
CLASSTYPE returnDifferentTypes(); // undefined
template<>
std::string returnDifferentTypes<std::string>() { // for 'std::string'
return std::string("returned string");
}
template<>
int returnDifferentTypes<int>() { // for 'int'
return 123;
}
template<>
double returnDifferentTypes<double>() { // for 'double'
return 123.123;
}
Run Code Online (Sandbox Code Playgroud)
用法:
string mapped = returnDifferentTypes<string>();
int mapped = returnDifferentTypes<int>();
Run Code Online (Sandbox Code Playgroud)