Choose function to apply based on the validity of an expression

前端 未结 4 1582
自闭症患者
自闭症患者 2021-01-01 17:28

The problem is the following, in C++14:

  • Let\'s have two functions FV&& valid_f, FI&& invalid_f, and argu
4条回答
  •  情话喂你
    2021-01-01 17:49

    Here's an alternative answer, just for kicks. We need a static_if:

    template  T&& static_if(std::true_type, T&& t, F&& ) { return std::forward(t); }
    template  F&& static_if(std::false_type, T&& , F&& f) { return std::forward(f); }
    

    And an is_callable. Since you're just supporting functions, we can do it as:

    template 
    struct is_callable : std::false_type { };
    
    template 
    struct is_callable()(std::declval()...))>>
    : std::true_type
    { };
    

    And then we can construct the logic in place:

    template 
    void apply_on_validity(FV&& valid_f, FI&& invalid_f, Args&&... args)
    {
        auto noop = [](auto&&...) {};
    
        static_if(
            is_callable{},
            std::forward(valid_f),
            static_if(
                std::is_callable{},
                std::forward(invalid_f),
                noop
            )
        )(std::forward(args)...);
    }
    

提交回复
热议问题