// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018 Intel Corporation #ifndef OPENCV_GAPI_UTIL_VARIANT_HPP #define OPENCV_GAPI_UTIL_VARIANT_HPP #include #include #include #include #include // max_of_t #include // A poor man's `variant` implementation, incompletely modeled against C++17 spec. namespace cv { namespace util { namespace detail { template struct type_list_index_helper { static const constexpr bool is_same = std::is_same::value; static const constexpr std::size_t value = std::conditional, type_list_index_helper>::type::value; }; template struct type_list_index_helper { static_assert(std::is_same::value, "Type not found"); static const constexpr std::size_t value = I; }; } template struct type_list_index { static const constexpr std::size_t value = detail::type_list_index_helper<0, Target, Types...>::value; }; template struct type_list_element { using type = typename std::tuple_element >::type; }; class bad_variant_access: public std::exception { public: virtual const char *what() const noexcept override { return "Bad variant access"; } }; // Interface /////////////////////////////////////////////////////////////// struct monostate {}; inline bool operator==(const util::monostate&, const util::monostate&) { return true; } template // FIXME: no references, arrays, and void class variant { // FIXME: Replace with std::aligned_union after gcc4.8 support is dropped static constexpr const std::size_t S = cv::detail::max_of_t::value; static constexpr const std::size_t A = cv::detail::max_of_t::value; using Memory = typename std::aligned_storage::type[1]; template struct cctr_h { static void help(Memory memory, const Memory from) { new (memory) T(*reinterpret_cast(from)); } }; template struct mctr_h { static void help(Memory memory, void *pval) { new (memory) T(std::move(*reinterpret_cast(pval))); } }; //FIXME: unify with cctr_h and mctr_h template struct cnvrt_ctor_h { static void help(Memory memory, void* from) { using util::decay_t; new (memory) decay_t(std::forward(*reinterpret_cast*>(from))); } }; template struct copy_h { static void help(Memory to, const Memory from) { *reinterpret_cast(to) = *reinterpret_cast(from); } }; template struct move_h { static void help(Memory to, Memory from) { *reinterpret_cast(to) = std::move(*reinterpret_cast(from)); } }; //FIXME: unify with copy_h and move_h template struct cnvrt_assign_h { static void help(Memory to, void* from) { using util::decay_t; *reinterpret_cast*>(to) = std::forward(*reinterpret_cast*>(from)); } }; template struct swap_h { static void help(Memory to, Memory from) { std::swap(*reinterpret_cast(to), *reinterpret_cast(from)); } }; template struct dtor_h { static void help(Memory memory) { (void) memory; // MSCV warning reinterpret_cast(memory)->~T(); } }; template struct equal_h { static bool help(const Memory lhs, const Memory rhs) { const T& t_lhs = *reinterpret_cast(lhs); const T& t_rhs = *reinterpret_cast(rhs); return t_lhs == t_rhs; } }; typedef void (*CCtr) (Memory, const Memory); // Copy c-tor (variant) typedef void (*MCtr) (Memory, void*); // Generic move c-tor typedef void (*Copy) (Memory, const Memory); // Copy assignment typedef void (*Move) (Memory, Memory); // Move assignment typedef void (*Swap) (Memory, Memory); // Swap typedef void (*Dtor) (Memory); // Destructor using cnvrt_assgn_t = void (*) (Memory, void*); // Converting assignment (via std::forward) using cnvrt_ctor_t = void (*) (Memory, void*); // Converting constructor (via std::forward) typedef bool (*Equal)(const Memory, const Memory); // Equality test (external) static constexpr std::array cctrs(){ return {{(&cctr_h::help)...}};} static constexpr std::array mctrs(){ return {{(&mctr_h::help)...}};} static constexpr std::array cpyrs(){ return {{(©_h::help)...}};} static constexpr std::array mvers(){ return {{(&move_h::help)...}};} static constexpr std::array swprs(){ return {{(&swap_h::help)...}};} static constexpr std::array dtors(){ return {{(&dtor_h::help)...}};} template struct conditional_ref : std::conditional::type&, typename std::remove_reference::type > {}; template using conditional_ref_t = typename conditional_ref::type; template static constexpr std::array cnvrt_assgnrs(){ return {{(&cnvrt_assign_h>::help)...}}; } template static constexpr std::array cnvrt_ctors(){ return {{(&cnvrt_ctor_h>::help)...}}; } std::size_t m_index = 0; protected: template friend T& get(variant &v); template friend const T& get(const variant &v); template friend T* get_if(variant *v) noexcept; template friend const T* get_if(const variant *v) noexcept; template friend bool operator==(const variant &lhs, const variant &rhs); Memory memory; public: // Constructors variant() noexcept; variant(const variant& other); variant(variant&& other) noexcept; // are_different_t is a SFINAE trick to avoid variant(T &&t) with T=variant // for some reason, this version is called instead of variant(variant&& o) when // variant is used in STL containers (examples: vector assignment). template< typename T, typename = util::are_different_t > explicit variant(T&& t); // template explicit variant(Args&&... args); // FIXME: other constructors // Destructor ~variant(); // Assignment variant& operator=(const variant& rhs); variant& operator=(variant &&rhs) noexcept; // SFINAE trick to avoid operator=(T&&) with T=variant<>, see comment above template< typename T, typename = util::are_different_t > variant& operator=(T&& t) noexcept; // Observers std::size_t index() const noexcept; // FIXME: valueless_by_exception() // Modifiers // FIXME: emplace() void swap(variant &rhs) noexcept; // Non-C++17x! template static constexpr std::size_t index_of(); }; // FIMXE: visit template T* get_if(util::variant* v) noexcept; template const T* get_if(const util::variant* v) noexcept; template T& get(util::variant &v); template const T& get(const util::variant &v); template typename util::type_list_element::type& get(util::variant &v); template const typename util::type_list_element::type& get(const util::variant &v); template bool holds_alternative(const util::variant &v) noexcept; // Visitor namespace detail { struct visitor_interface {}; // Class `visitor_return_type_deduction_helper` // introduces solution for deduction `return_type` in `visit` function in common way // for both Lambda and class Visitor and keep one interface invocation point: `visit` only // his helper class is required to unify return_type deduction mechanism because // for Lambda it is possible to take type of `decltype(visitor(get<0>(var)))` // but for class Visitor there is no operator() in base case, // because it provides `operator() (std::size_t index, ...)` // So `visitor_return_type_deduction_helper` expose `operator()` // uses only for class Visitor only for deduction `return type` in visit() template struct visitor_return_type_deduction_helper { using return_type = R; // to be used in Lambda return type deduction context only template return_type operator() (T&&); }; } // Special purpose `static_visitor` can receive additional arguments template struct static_visitor : public detail::visitor_interface, public detail::visitor_return_type_deduction_helper { // assign responsibility for return type deduction to helper class using return_type = typename detail::visitor_return_type_deduction_helper::return_type; using detail::visitor_return_type_deduction_helper::operator(); friend Impl; template return_type operator() (std::size_t index, VariantValue&& value, Args&& ...args) { suppress_unused_warning(index); return static_cast(this)-> visit( std::forward(value), std::forward(args)...); } }; // Special purpose `static_indexed_visitor` can receive additional arguments // And make forwarding current variant index as runtime function argument to its `Impl` template struct static_indexed_visitor : public detail::visitor_interface, public detail::visitor_return_type_deduction_helper { // assign responsibility for return type deduction to helper class using return_type = typename detail::visitor_return_type_deduction_helper::return_type; using detail::visitor_return_type_deduction_helper::operator(); friend Impl; template return_type operator() (std::size_t Index, VariantValue&& value, Args&& ...args) { return static_cast(this)-> visit(Index, std::forward(value), std::forward(args)...); } }; template struct variant_size; template struct variant_size> : std::integral_constant { }; // FIXME: T&&, const TT&& versions. // Implementation ////////////////////////////////////////////////////////// template variant::variant() noexcept { typedef typename std::tuple_element<0, std::tuple >::type TFirst; new (memory) TFirst(); } template variant::variant(const variant &other) : m_index(other.m_index) { (cctrs()[m_index])(memory, other.memory); } template variant::variant(variant &&other) noexcept : m_index(other.m_index) { (mctrs()[m_index])(memory, other.memory); } template template variant::variant(T&& t) : m_index(util::type_list_index, Ts...>::value) { const constexpr bool is_lvalue_arg = std::is_lvalue_reference::value; (cnvrt_ctors()[m_index])(memory, const_cast *>(&t)); } template variant::~variant() { (dtors()[m_index])(memory); } template variant& variant::operator=(const variant &rhs) { if (m_index != rhs.m_index) { (dtors()[ m_index])(memory); (cctrs()[rhs.m_index])(memory, rhs.memory); m_index = rhs.m_index; } else { (cpyrs()[rhs.m_index])(memory, rhs.memory); } return *this; } template variant& variant::operator=(variant &&rhs) noexcept { if (m_index != rhs.m_index) { (dtors()[ m_index])(memory); (mctrs()[rhs.m_index])(memory, rhs.memory); m_index = rhs.m_index; } else { (mvers()[rhs.m_index])(memory, rhs.memory); } return *this; } template template variant& variant::operator=(T&& t) noexcept { using decayed_t = util::decay_t; // FIXME: No version with implicit type conversion available! const constexpr std::size_t t_index = util::type_list_index::value; const constexpr bool is_lvalue_arg = std::is_lvalue_reference::value; if (t_index != m_index) { (dtors()[m_index])(memory); (cnvrt_ctors()[t_index])(memory, &t); m_index = t_index; } else { (cnvrt_assgnrs()[m_index])(memory, &t); } return *this; } template std::size_t util::variant::index() const noexcept { return m_index; } template void variant::swap(variant &rhs) noexcept { if (m_index == rhs.index()) { (swprs()[m_index](memory, rhs.memory)); } else { variant tmp(std::move(*this)); *this = std::move(rhs); rhs = std::move(tmp); } } template template constexpr std::size_t variant::index_of() { return util::type_list_index::value; // FIXME: tests! } template T* get_if(util::variant* v) noexcept { const constexpr std::size_t t_index = util::type_list_index::value; if (v && v->index() == t_index) return (T*)(&v->memory); // workaround for ICC 2019 // original code: return reinterpret_cast(v.memory); return nullptr; } template const T* get_if(const util::variant* v) noexcept { const constexpr std::size_t t_index = util::type_list_index::value; if (v && v->index() == t_index) return (const T*)(&v->memory); // workaround for ICC 2019 // original code: return reinterpret_cast(v.memory); return nullptr; } template T& get(util::variant &v) { if (auto* p = get_if(&v)) return *p; else throw_error(bad_variant_access()); } template const T& get(const util::variant &v) { if (auto* p = get_if(&v)) return *p; else throw_error(bad_variant_access()); } template typename util::type_list_element::type& get(util::variant &v) { using ReturnType = typename util::type_list_element::type; return const_cast(get(static_cast &>(v))); } template const typename util::type_list_element::type& get(const util::variant &v) { static_assert(Index < sizeof...(Types), "`Index` it out of bound of `util::variant` type list"); using ReturnType = typename util::type_list_element::type; return get(v); } template bool holds_alternative(const util::variant &v) noexcept { return v.index() == util::variant::template index_of(); } template bool operator==(const variant &lhs, const variant &rhs) { using V = variant; // Instantiate table only here since it requires operator== for // should have operator== only if this one is used, not in general static const std::array eqs = { {(&V::template equal_h::help)...} }; if (lhs.index() != rhs.index()) return false; return (eqs[lhs.index()])(lhs.memory, rhs.memory); } template bool operator!=(const variant &lhs, const variant &rhs) { return !(lhs == rhs); } namespace detail { // terminate recursion implementation for `non-void` ReturnType template ReturnType apply_visitor_impl(Visitor&&, Variant&, std::true_type, std::false_type, VisitorArgs&& ...) { return {}; } // terminate recursion implementation for `void` ReturnType template void apply_visitor_impl(Visitor&&, Variant&, std::true_type, std::true_type, VisitorArgs&& ...) { } // Intermediate resursion processor for Lambda Visitors template typename std::enable_if::type>::value, ReturnType>::type apply_visitor_impl(Visitor&& visitor, Variant&& v, std::false_type not_processed, std::integral_constant should_no_return, VisitorArgs&& ...args) { static_assert(std::is_same(v)))>::value, "Different `ReturnType`s detected! All `Visitor::visit` or `overload_lamba_set`" " must return the same type"); suppress_unused_warning(not_processed); if (v.index() == CurIndex) { return visitor.operator()(get(v), std::forward(args)... ); } using is_variant_processed_t = std::integral_constant= ElemCount>; return apply_visitor_impl( std::forward(visitor), std::forward(v), is_variant_processed_t{}, should_no_return, std::forward(args)...); } //Visual Studio 2014 compilation fix: cast visitor to base class before invoke operator() template typename std::enable_if::type>, typename std::decay::type>::value, ReturnType>::type invoke_class_visitor(Visitor& visitor, Value&& v, VisitorArgs&&...args) { return static_cast::type>&>(visitor).operator() (CurIndex, std::forward(v), std::forward(args)... ); } //Visual Studio 2014 compilation fix: cast visitor to base class before invoke operator() template typename std::enable_if::type>, typename std::decay::type>::value, ReturnType>::type invoke_class_visitor(Visitor& visitor, Value&& v, VisitorArgs&&...args) { return static_cast::type>&>(visitor).operator() (CurIndex, std::forward(v), std::forward(args)... ); } // Intermediate recursion processor for special case `visitor_interface` derived Visitors template typename std::enable_if::type>::value, ReturnType>::type apply_visitor_impl(Visitor&& visitor, Variant&& v, std::false_type not_processed, std::integral_constant should_no_return, VisitorArgs&& ...args) { static_assert(std::is_same(v)))>::value, "Different `ReturnType`s detected! All `Visitor::visit` or `overload_lamba_set`" " must return the same type"); suppress_unused_warning(not_processed); if (v.index() == CurIndex) { return invoke_class_visitor(visitor, get(v), std::forward(args)... ); } using is_variant_processed_t = std::integral_constant= ElemCount>; return apply_visitor_impl( std::forward(visitor), std::forward(v), is_variant_processed_t{}, should_no_return, std::forward(args)...); } } // namespace detail template auto visit(Visitor &visitor, const Variant& var, VisitorArg &&...args) -> decltype(visitor(get<0>(var))) { constexpr std::size_t varsize = util::variant_size::value; static_assert(varsize != 0, "utils::variant must contains one type at least "); using is_variant_processed_t = std::false_type; using ReturnType = decltype(visitor(get<0>(var))); using return_t = std::is_same; return detail::apply_visitor_impl( std::forward(visitor), var, is_variant_processed_t{}, return_t{}, std::forward(args)...); } template auto visit(Visitor&& visitor, const Variant& var) -> decltype(visitor(get<0>(var))) { constexpr std::size_t varsize = util::variant_size::value; static_assert(varsize != 0, "utils::variant must contains one type at least "); using is_variant_processed_t = std::false_type; using ReturnType = decltype(visitor(get<0>(var))); using return_t = std::is_same; return detail::apply_visitor_impl( std::forward(visitor), var, is_variant_processed_t{}, return_t{}); } } // namespace util } // namespace cv #endif // OPENCV_GAPI_UTIL_VARIANT_HPP