开发者

c++: good name for argument argument conversion classes

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.


  1. As you are probably aware, in C++ "accepted/common" depends on the platform you're running on. A Unix C++ program defers in conventions from a WIN32 C++ program, for example. That said, I haven't seen these kinds of classes very often, for obvious reasons: they incur a performance overhead. You are creating a new object on every call to the function, which is rather unnecessary. It does save you some code, though, so it may be worth it in specific cases, but still it should be carefully considered.

  2. As far as I know there is no way in C++ to restrict a class t be used only as a parameter. At least they cannot be instantiated without receiving one of the supported types in their constructors. One thing I'm thinking about is that you should probably support a copy ctor to allow passing the converter class itself between calls (if you have two separate function sets like you described, and one calls the other).


What's wrong with overloads ? It's perfectly safe to define Foo(X) that is implemented using Foo(Bar(X)). I think it's clearer that crafting wrapper classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜