c\c++ - Functions with unions as arguments to meet specific requirements -
i'm engineering library provide functionality 1 device. device has common operations different algorithms accomplish these operations. want 1 function prototype 1 particular operation, not bunch of them, instead of:
alg1_foo(); alg2_foo(); ... i want this:
foo(alg); but don't want pass alg separate argument, because functions have lot of arguments without it, have arguments identification and/or authorization of device, in argument, out argument (at least 1 of them), think annoying add alg separate argument.
so idea provide solution one:
foo(const someunion& some_union); where:
union someunion { algid alg_id; alg1::somestruct alg1_some_struct; alg2::somestruct alg2_some_struct; someunion(alg1::somestruct some_struct) { alg1_some_struct = some_struct; }; someunion(alg2::somestruct some_struct) { alg2_some_struct = some_struct; }; }; and structures of particular algorithms this:
namespace alg1 { struct somestruct { static const algid alg_id = alg1; . . . }; } so if want perform alg1, pass appropriate structure foo , works in c++, say
alg1::somestruct a; foo(a); but want library maintain possibilities of pure c. of course need to:
remove references , replace them pointers;
remove namespaces (we can still emulate them of structures (this thread may helpful interested: namespaces in c);
replace c++-style of defining structs c , define name in tag namespace (typedef struct tagstruct {...} struct;);
remove functions inside structures , unions.
but though can't understand if it's possible accomplish want maintenance of c... see way? or simplier pass alg_id separate argument not bother unions , structures (but want avoid if possible)?
to me, seems typical case trying solve problem "the wrong way".
if have "lots of arguments" function, using struct fine. hiding "which function calling" inside such struct, , having several variants ofstruct inside union, we're trying stuff 1 function. start split function takes 1 struct - remove union argument - that's wrong. [i have worked code similar things - chances of sneaking in code wrong thing , causes hard find error because passed wrong type of union arguments function makes poor solution]. if pass wrong type of structure plain functions compiler tells you. if fill in wrong part of union, code using "right" part of structure "weird" data [quite possibly undefined behaviour] - type of bug can darn difficult find.
so yes, split functions, remove union!
edit: 1 suggestion comes mind if wish have simple , consistent interface have factory function, pass alg_id to, returns function pointer relevant function. unfortunately, if interface each function suggest, different structure, still have potential getting data structures , functions mixed up, cut down on number of "published functions" - in fact, functions don't need visible @ outside of module [library or object file] provides them.
Comments
Post a Comment