tags:

views:

190

answers:

1

Let's suppose I am writing a function template GCD which uses both operator/ and operator%. For some types, for example, complex numbers or polynomials both can be computed efficiently (i.e. when dividing polynomials you get remainder "for free"). So some of my class templates have divmod implemented, which returns a pair of quotient and remainder.

However some classes and notably built-in types, such as int, do not have divmod (or equivalent) implemented. If I was about to write one GCD which uses divmod I would discriminate against the other types (and vice versa). I haven't been able to come up with a template specialization which wouldn't require most of the code for GCD to be repeated.

What are my options here?

+3  A: 

I would go for type traits and template specializations based on that. You can use metaprogramming to determine if the type has divmod, and based on that provide specific parts of a general algorithm. That is, extract the common part of the algorithm into a generic piece of code that calls specialized functions for the differing parts based on the typetraits.

Take a look at boost::type_traits library to get on the way of the type traits implementation, and policy based design for ideas on how to inject different behaviors in a common code base by means of (policy) templates.

David Rodríguez - dribeas
thanks, I guess your answer and http://www.ddj.com/cpp/184404270#l4 will get me going!