gpt4 book ai didi

C++ 避免 if & 硬编码字符串

转载 作者:行者123 更新时间:2023-11-27 23:51:24 28 4
gpt4 key购买 nike

有没有办法避免在函数重定向中使用 if 和硬编码字符串,想法是接收一个字符串并调用适当的函数,可能使用模板/元编程..

#include <string>
#include <iostream>

void account()
{
std::cout << "accout method" << std::endl;
}

void status()
{
std::cout << "status method" << std::endl;
}

void redirect(std::string method_to_call)
{
if(method_to_call == "account")
{
account();
}
else if(method_to_call == "status")
{
status();
}
else
{
std::cout << "method not found!!" << std::endl;
}
}

int main()
{
std::string method_name;
std::cin >> method_name;

redirect(method_name);

return 0;
}

最佳答案

您可以使用 std::map 和 std::function 来实现这一点,尽管它在插入点仍然需要一个“硬编码”字符串。

void status() 
{
std::cout << "status" << std::endl;
}

void account()
{
std::cout << "account" << std::endl;
}

int main()
{
std::map< std::string, std::function<void()> > functions;

functions.emplace( "status" , status );
functions.emplace( "account", account );

std::string method_name;
std::cin >> method_name;

auto iter( functions.find( method_name ) );
if( iter != functions.end() )
{
iter->second();
}
else
{
std::cout << "Method " << method_name << " not found!!" << std::endl;
}
}

如果你愿意使用宏,那么你可以像这样避免额外的字符串:

#define ADD_FUNCTION( map, func ) map.emplace( #func, func );

std::map< std::string, std::function< void() > > functions;
ADD_FUNCTION( functions, status );
ADD_FUNCTION( functions, account );

关于C++ 避免 if & 硬编码字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46130117/

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