3 ms·
Static if, resurrected
- pbsd 11y agoI'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)...); }
- sedeki 11y agoSorry for being off-topic, but where did you learn to write this solid C++ of yours?
- pbsd 11y agoI'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.
- xutopia 11y agoWhat a horrible domain name!