C++ – Are generic programming and OOP mutually exclusive

cgeneric-programming

I never did generic programming before, being more of a python guy, and generally using OOP. As I moved into generic programming, I faced some issues. I read the FAQ, but I am not satisfied. What I want to ask are the following questions (I am mostly interested in the first, but answering the others will be extremely welcome):

Are generic programming and OOP mutually exclusive? Meaning, for example, are you supposed to have methods and functions accepting the template, instead of baseclass or abstract pure class?


Some other questions I've got, only to provide context to my lack of understanding are: How do traditional design patterns react to generic programming approach and concepts? How to prevent (or control) the genericity of each class/template to "bubble up" in the dependencies dictated by the program logic, in particular when two types are related and go always together (e.g. a RealNumberProducer class and double vs ComplexNumberProducer and std::complex)?

Best Answer

Nope. In fact, many of the best systems use both in combination. Containers are worthless if they are not generic- case in point, Java or C#'s containers when those languages were launched.

Indeed, generic programming is virtually identical to OOP, except that it occurs at compilation/interpretation time rather than execution time, which has a large number of advantages, including increased performance, safety, and flexibility.

are generic programming and OOP mutually exclusive? Meaning, for example, are you supposed to have methods and functions accepting the template, instead of baseclass or abstract pure class?

They are not mutually exclusive, but you should use templates whenever possible to achieve a generic method. Do not ever use inheritance unless you cannot use a template. Inheritance is one of the worst tools that is in the arsenal.

How do traditional design patterns react to generic programming approach and concepts?

They get absolutely blown out of the water. Some patterns are simply completely worthless to begin with (e.g. Singleton), many others are useless in the face of templates or all possible instances of them are implemented directly by one template, such as Listener.

How to prevent (or control) the genericity of each class/template to "bubble up" in the dependencies dictated by the program logic, in particular when two types are related and go always together (e.g. a RealNumberProducer class and double vs ComplexNumberProducer and std::complex)?

Don't. Encourage it. Also, I'm just guessing by the names here, but that really just sounds like std::function<double(args)>, rather than an actual class.

Related Topic