From 06cfc1d0b6377cf4d01f3ce2cda9b47059704816 Mon Sep 17 00:00:00 2001 From: rexy712 Date: Fri, 27 Mar 2020 21:28:05 -0700 Subject: [PATCH] Add default dispatch handling for generic case of 'const rjp::value&'. Will cause compilation error if return type is not void --- rjp++/include/dispatch.hpp | 29 +++++++++++++++++++++++++++++ rjp++/tests/dispatch.cpp | 4 +++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/rjp++/include/dispatch.hpp b/rjp++/include/dispatch.hpp index 0ece839..98b656d 100644 --- a/rjp++/include/dispatch.hpp +++ b/rjp++/include/dispatch.hpp @@ -4,9 +4,17 @@ #include "rjp_internal.hpp" #include //is_same, true_type, false_type #include //forward +#include namespace rjp{ + class missing_dispatch_handler : public std::exception + { + public: + const char* what(void)const noexcept override{ + return "Argument not handled in rjp::dispatch"; + } + }; namespace detail{ template struct to_value_type; @@ -81,6 +89,23 @@ namespace rjp{ struct has_next_data_type{ static constexpr bool value = has_next_data_type_helper::value; }; + + template + struct has_operator_for{ + template()(std::declval()))> + static std::true_type check(U*); + static std::false_type check(...); + + static constexpr bool value = std::is_same::value; + }; + template + struct has_operator_for_any{ + static constexpr bool value = has_operator_for::value || has_operator_for_any::value; + }; + template + struct has_operator_for_any{ + static constexpr bool value = has_operator_for::value; + }; template decltype(auto) dispatch_helper(Func&& fun, Val&& v){ if(v.type() == T){ @@ -89,6 +114,7 @@ namespace rjp{ if constexpr(detail::has_next_data_type::value){ return dispatch_helper::value>(std::forward(fun), std::forward(v)); } + throw missing_dispatch_handler{}; //deals with -Wreturn-type warnings } } template @@ -99,6 +125,9 @@ namespace rjp{ struct dispatcher : public Ts... { using Ts::operator()...; + + template::value,void>::type* = nullptr> + decltype(auto) operator()(const value&)const{} }; template diff --git a/rjp++/tests/dispatch.cpp b/rjp++/tests/dispatch.cpp index 1488e77..db8c3a3 100644 --- a/rjp++/tests/dispatch.cpp +++ b/rjp++/tests/dispatch.cpp @@ -29,20 +29,22 @@ rjp::array initialize_array(int num){ int main(){ srand(time(0)); + int retval = 0; rjp::array root = initialize_array(NUM_ELEMENTS); for(auto&& val : root){ RJP_data_type d; rjp::dispatch(rjp::dispatcher{ - [&d](const rjp::value&){assert(false);}, [&d](const rjp::integer&){d = rjp_json_integer;}, [&d](const rjp::boolean&){d = rjp_json_boolean;}, [&d](const rjp::array&){d = rjp_json_array;}, [&d](const rjp::object&){d = rjp_json_object;}, }, val); if(d != val.type()){ + ++retval; printf("Dispatch error\n"); } } + return retval; }