gpt4 book ai didi

c++ - 如何从字符串中检测数据类型?

转载 作者:行者123 更新时间:2023-11-30 03:54:29 25 4
gpt4 key购买 nike

有一个伪代码:

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++ 解决方案。

最佳答案

虽然模板函数不能直接实现这一点,但我建议使用 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> . map 必须在使用前进行初始化。静态常量表不需要在运行时初始化。

关于c++ - 如何从字符串中检测数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29474684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com