1

What is considered "good practice" in handling unwanted data types for templated classes?

Let's say we have a function in a templated class that does number multiplication, but the driver file for the class declares an instance of the class with Type string.

I've been given the argument that this is a "personal problem" for whoever's creating the driver file, and that all that needs to be done on your part is proper function prologues in the header/implementation files.

I'm wondering if there is a general practice used with templates regarding this issue. Do you check your Types in a class before handling them (I guess, to a certain extent that defeats the purpose of a template), or do you define behavior for specific types (though this also seems like a defeat of purpose)?

Or do you simply document your code correctly and let the programmer who uses your class take the precautions?

skippr
  • 2,656
  • 3
  • 24
  • 39
  • Isn't this the same question as http://stackoverflow.com/questions/148373/c-restrict-template-function – Guillaume Schub Mar 21 '12 at 17:51
  • @GuillaumeSchub That was a specific case on restricting certain data types. I'm asking a wider-scope question; wondering what common practices are applied with this type of situation, where you want to account for cases (if at all) of what could be considered an incorrect data type. – skippr Mar 21 '12 at 20:23

1 Answers1

2

I'd generally use something like Boost/C++11 static_assert to assert the properties you want This will not only let you assure that it's numeric, but has things like is_signed and is_integer to assure more detail about the type, if you need/want to.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111