Function with variable parameter size: How to conditionally set some arguments?

前端 未结 2 1182
独厮守ぢ
独厮守ぢ 2020-12-20 07:46

To create a boost::process with output redirection, you should do:

bp::ipstream out;
bp::child c(\"c++filt\", std_out > out);

Now, what

2条回答
  •  一向
    一向 (楼主)
    2020-12-20 08:06

    The fancy boost::process API revolves around supplying handler objects implementing on_setup, on_error, on_success (and potentially some more, depending on current OS) methods that will be executed at process construction call in context of some internal process launcher and will be able to alter process launcher behavior. std_out > out is an overloaded operator that will return such handler. More information can be found at boost process Extensions documentation.

    So the generic way to conditionally control the redirection and other parameters would be to write generic handler proxy accepting optional real handler and calling appropriate methods of real handler:

    #include 
    #include 
    #include 
    
    #include 
    #include 
    
    template class
    t_OptionalHandler
    :    public ::boost::process::extend::handler
    {
        private: using t_OptionalRealHandler = ::boost::optional;
    
        private: t_OptionalRealHandler m_real_handler;
    
        public:
        t_OptionalHandler(void)
        :   m_real_handler{}
        {}
    
        public: explicit
        t_OptionalHandler(TRealHandler && real_handler)
        :   m_real_handler{::std::move(real_handler)}
        {}
    
        template
        void on_setup(TExecutor & e) const
        {
            if(m_real_handler)
            {
                m_real_handler.get().on_setup(e);
            }
        }
    
        template
        void on_error(TExecutor & e, const std::error_code & code) const
        {
            if(m_real_handler)
            {
                m_real_handler.get().on_error(e, code);
            }
        }
    
        template
        void on_success(TExecutor & e) const
        {
            if(m_real_handler)
            {
                m_real_handler.get().on_success(e);
            }
        }
    };
    
    int main()
    {
        bool const need_to_redirect{false};
        ::std::unique_ptr<::boost::process::ipstream> const p_stream
        {
            need_to_redirect?
            new ::boost::process::ipstream{}
            :
            nullptr
        };
        using t_OptionalStdOutRedirectionHandler = t_OptionalHandler
        <
            decltype(::boost::process::std_out > *p_stream)
         >;
        ::boost::process::child ch
        (
            "cmd"
        ,   need_to_redirect?
            t_OptionalStdOutRedirectionHandler{::boost::process::std_out > *p_stream}
            :
            t_OptionalStdOutRedirectionHandler{}
        );
        ch.wait();
        return(0);
    }
    

提交回复
热议问题