Choose function to apply based on the validity of an expression

前端 未结 4 1599
自闭症患者
自闭症患者 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:46

    Take:

    template  struct rank : rank {};
    template <> struct rank<0> {};
    

    and then:

    template 
    auto apply_on_validity_impl(rank<2>, FV&& valid_f, FI&& invalid_f, Args&&... args)
        -> decltype(std::forward(valid_f)(std::forward(args)...), void())
    {
        std::forward(valid_f)(std::forward(args)...);
    }
    
    template 
    auto apply_on_validity_impl(rank<1>, FV&& valid_f, FI&& invalid_f, Args&&... args)
        -> decltype(std::forward(invalid_f)(std::forward(args)...), void())
    {
        std::forward(invalid_f)(std::forward(args)...);
    }
    
    template 
    void apply_on_validity_impl(rank<0>, FV&& valid_f, FI&& invalid_f, Args&&... args)
    {
    
    }
    
    template 
    void apply_on_validity(FV&& valid_f, FI&& invalid_f, Args&&... args)
    {
        return apply_on_validity_impl(rank<2>{}, std::forward(valid_f), std::forward(invalid_f), std::forward(args)...);
    }
    

    DEMO

提交回复
热议问题