代码之家  ›  专栏  ›  技术社区  ›  Basti An

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

c++
  •  -4
  • Basti An  · 技术社区  · 7 年前

    如何根据启动参数创建在运行时创建的开关函数。 我的程序在启动时从JSON加载它的配置。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Dmitry Sazonov    7 年前

    最简单的方法是使用函子映射来处理选项。但这取决于你的任务。大概是这样的:

    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 );
    }