Choose function to apply based on the validity of an expression

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

    Piotr Skotnicki's answer is superb, but code like that makes me feel compelled to point out how much cleaner C++17 will be thanks to constexpr if and additional type traits like is_callable: Demo Demo*This version creates more warnings but is simpler

    template 
    void apply_on_validity(FV&& valid_f, FI&& invalid_f, Args&&... args)
    {
        if constexpr (std::is_callable_v)
            std::cout << "Apply valid_f by default\n";
        else
        {
            if constexpr (std::is_callable_v)
                std::cout << "Apply invalid_f if valid_f does not work\n";
            else
                std::cout << "Do nothing when neither valid_f nor invalid_f work\n";
        }
    }
    

提交回复
热议问题