Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic/template programming best practices: To limit types, or not to limit types

That is my question. I'm just curious what the consensus is on limiting the types that can be passed in to a generic function or class. I thought I had read at some point, that if you're doing generic programming, it was generally better to leave things open instead of trying to close them down (don't recall the source).

I'm writing a library that has some internal generic functions, and I feel that they should only allow types within the library to be used with them, simply because that's how I mean for them to be used. On the other hand, I'm not really sure my effort to lock things down is worth it.

Anybody maybe have some sources for statistics or authoritative commentary on this topic? I'm also interested in sound opinions. Hopefully that doesn't invalidate this question altogether :\

Also, are there any tags here on SO that equate to "best-practice"? I didn't see that one specifically, but it seems like it'd be helpful to be able to bring up all best-practice info for a given SO topic... maybe not, just a thought.

Edit: One answer so far mentioned that the type of library I'm doing would be significant. It's a database library that ends up working with STL containers, variadics (tuple), Boost Fusion, things of that nature. I can see how that would be relevant, but I'd also be interested in rules of thumb for determining which way to go.

like image 800
Brett Rossier Avatar asked May 18 '11 16:05

Brett Rossier


2 Answers

Always leave it as open as possible - but make sure to

  • document the required interface and behaviour for valid types to use with your generic code.
  • use a type's interface characteristics (traits) to determine whether to allow/disallow it. Don't base your decision on the type name.
  • produce reasonable diagnosis if someone uses a wrong type. C++ templates are great at raising tons of deeply-nested errors if they get instanced with the wrong types - using type traits, static assertions and related techniques, one can easily produce more succinct error messages.
like image 112
Alexander Gessler Avatar answered Oct 20 '22 04:10

Alexander Gessler


In my database framework, I decided to forgo templates and use a single base class. Generic programming meant that any or all objects can be used. The specific type classes outweighed the few generic operations. For example, strings and numbers can be compared for equality; BLOBs (Binary Large OBjects) may want to use a different method (such as comparing MD5 checksums stored in a different record).

Also, there was an inheritance branch between strings and numeric types.

By using an inheritance hierarchy, I can refer to any field by using the Field class or to a specialized class such as Field_Int.

like image 22
Thomas Matthews Avatar answered Oct 20 '22 04:10

Thomas Matthews