最简单的方法是使用函子映射来处理选项。但这取决于你的任务。大概是这样的:
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 );
}