Hacker News new | past | comments | ask | show | jobs | submit login
Static if, resurrected (open-std.org)
37 points by ScottWRobinson on July 17, 2015 | hide | past | favorite | 4 comments



I'm not particularly convinced. The make_unique example given could be implemented in a similar manner with existing C++ features, and it would not require yet another complexity-inducing feature into C++:

    #include <memory>
    #include <type_traits>
    #include <utility>

    template<bool Cond>
    struct static_if_impl {
      template<typename F1, typename F2, typename...Args>
      decltype(auto) operator()(F1 f1, F2, Args&&...args) const {
        return f1(std::forward<Args>(args)...);
      }
    };
    
    template<>
    struct static_if_impl<false> {
      template<typename F1, typename F2, typename...Args>
      decltype(auto) operator()(F1, F2 f2, Args&&...args) const {
        return f2(std::forward<Args>(args)...);
      }
    };
    
    template<bool Cond>
    constexpr static_if_impl<Cond> static_if{};
    
    template <class T, class... Args> 
    std::unique_ptr<T> make_unique(Args&&... args) {
        return static_if<std::is_constructible<T, Args...>{}>([](auto&&...args) {
            return unique_ptr<T>(new T(std::forward<Args>(args)...));
        }, [](auto&&...args) {
            return unique_ptr<T>(new T{std::forward<Args>(args)...});
        }, std::forward<Args>(args)...);
    }


Sorry for being off-topic, but where did you learn to write this solid C++ of yours?


I'm not sure if you are being sarcastic, but to be honest I don't really remember. I guess I picked it up over time from here and there. Then moved on to more formal documentation, that is, the standards.


What a horrible domain name!




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: