如何从字符串中检测数据类型?
How to detect data types from string?
有一个伪代码:
s = input()
if s == 'int':
func<int>(...)
if s == 'char':
func<char>(...)
and there're more if blocks
如何编写无需任何 if
即可执行此操作的代码。喜欢下面的代码:
s = input()
func<s>(...) #auto detect type in s
我需要一个 C++ 的解决方案。
虽然模板函数不能直接做到这一点,但我建议 table 查找 std::string
与函数指针。
例如:
typedef void (*Function_Pointer_Type)(void);
struct Table_Entry
{
char const * data_type_name;
Function_Pointer_Type data_type_function;
};
void Process_Int(void);
void Process_Double(void);
static const Table_Entry data_type_function_table[] =
{
{"int", Process_Int},
{"double", Process_Double},
};
static const unsigned int number_of_data_types =
sizeof(data_type_function_table) / sizeof(data_type_function_table[0]);
// ...
for (unsigned int i = 0; i < number_of_data_types; ++i)
{
if (s == data_type_function_table[i].data_type_name)
{
data_type_function_table.data_type_function();
break;
}
}
另一种方法是使用std::map<std::string, Function_Pointer_Type>
。地图必须在使用前进行初始化。静态常量 table 不需要在运行时初始化。
有一个伪代码:
s = input()
if s == 'int':
func<int>(...)
if s == 'char':
func<char>(...)
and there're more if blocks
如何编写无需任何 if
即可执行此操作的代码。喜欢下面的代码:
s = input()
func<s>(...) #auto detect type in s
我需要一个 C++ 的解决方案。
虽然模板函数不能直接做到这一点,但我建议 table 查找 std::string
与函数指针。
例如:
typedef void (*Function_Pointer_Type)(void);
struct Table_Entry
{
char const * data_type_name;
Function_Pointer_Type data_type_function;
};
void Process_Int(void);
void Process_Double(void);
static const Table_Entry data_type_function_table[] =
{
{"int", Process_Int},
{"double", Process_Double},
};
static const unsigned int number_of_data_types =
sizeof(data_type_function_table) / sizeof(data_type_function_table[0]);
// ...
for (unsigned int i = 0; i < number_of_data_types; ++i)
{
if (s == data_type_function_table[i].data_type_name)
{
data_type_function_table.data_type_function();
break;
}
}
另一种方法是使用std::map<std::string, Function_Pointer_Type>
。地图必须在使用前进行初始化。静态常量 table 不需要在运行时初始化。