In C++, I sometimes end up with utility classes like this:
struct time_ref
{
time_ref(FILETIME & ft) : ftval(&ft), ttval(0) {}
time_ref(time_t & tt) : ttval(&tt), ftval(0) {}
FILETIME * ftval;
time_t * ttval;
}
They rely on implcit conversions e.g. to reduce the numner of overloads:
void Foo(int x, int y, time_ref t)
Rationale: if Foo has another parameter with overloads, the prototypes multiply, e.g. 3 overloads for X * 2 overloads for t is 6 prototypes, compared to 3 with above converter (or even one if two converters are used).
They always:
- have implicit constructors for two or mroe types
- should be used only as function parameters to enable these conversions
Thye differ in:
- Number of types supported
- can store a value, or a reference
- how the callee detects what type was provided (in the case above, it’s the non-null pointer. Another typical implementation is an enum field and a union of data values)
Questions:
1. Is there an accepted / common name for this pattern? I usually call them “argument converter” or “argument adapter”, which doesn’t seem common
2. any recommendaitons to formalize them – e.g. is there a way (apart from adding a comment saying so) to ensure they are used only as parameters? Any other things to be aware of?
A shim is often a good choice when you need to handle many different argument types, even after your interface is “done”. It allows you to do the conversion in a modular, fairly reusable way. See this wikipedia entry and its referenced articles for more information.