动态开关取决于启动时加载的参数



如何创建开关函数,该函数是在运行时创建的,具体取决于启动参数。我的程序在启动期间从JSON加载它的配置。对于JSON文件中的每个条目,switch函数中都应该有一个条目。

最简单的方法是使用函数映射来处理选项。但这确实取决于你的任务。类似这样的东西:

std::map< std::string, std::function< void( const std::string& ) > > handlers;
// In can be std::variant instead of std::string
handlers[ "key1" ] = []( const std::string& value )
{
std::cout << "Processing key1 in JSON, value is = " << value ;
};
handlers[ "key2" ] = []( const std::string& value )
{
std::cout << "Processing key1 in JSON, value is = " << value ;
}; //...
defaultHandler = [](const std::string&)
{
throw "Not supported param";
};
// Somehow iterate, depends on your json parser
// Can be recursive
for ( const auto& keyVal : json ) 
{
const auto& key = keyVal.first; // JSON key
const auto& value= keyVal.second; // JSON value
const auto itHandler = handlers.find( key ); // Looking for handler
if ( itHandler != handlers.end() )
{
const auto& handler = itHandler.second;
handler( value ); // Use handler, it's a "content" of your "case" block
}
else
defaultHandler( value );
}

最新更新