How do I transform a large, often-used C++ macro with trivial per-use changes into a C++ template or similar? -
i'm working on container, has code similar following pseudocode:
#define large_insert_macro (assignment_object) \ if (some_stuff) \ { \ ... more stuff ... \ allocator.construct(place_to_insert_to, assignment_object); \ ... etc ... \ } \ else if (other_stuff) \ { \ ... different stuff ... \ allocator.construct(place_to_insert_to, assignment_object); \ ... etc ... \ } \ else \ { \ ... other different stuff ... \ allocator.construct(place_to_insert_to, assignment_object); \ ... etc ... \ } \ ... more stuff again... \ iterator insert(the_type &object) { large_insert_macro(object) } iterator insert(the_type &&object) { large_insert_macro(std::move(object)) } template<typename... arguments> iterator emplace(arguments... parameters) { large_insert_macro(parameters...) }
given fact code before , after each insertion type both necessary insertion, not change between insertion types , cannot factored away 2 separate 'before , after' functions, how can piece of (pseudo)code changed no longer uses macros?
as always, stay on topic of changing macros other code forms - please.
the answer dump large insert macro altogether , allow wonder of universal reference deduction work you:
template<class thetype> iterator insert(thetype&& object) // object deduced either r-value // or l-value reference required context { if(some_stuff) { ... return allocator.construct(place_to_insert_to, std::forward<thetype>(object)); } else { ... , on } }
emplace without template argument @ call site possible when it's member function of container knows type contains. otherwise have specify it. again, note use of universal reference deduction perfect forwarding of arguments.
template<class thetype, typename... arguments> iterator emplace(arguments&&... parameters) { return insert(thetype(std::forward<arguments>(parameters)...)); }
Comments
Post a Comment