Monday, August 19, 2013

When might it make sense to use inheritance when templates (compile-time polymorphism) is enough?

Newsgroup: comp.lang.c++

Subject: When might it make sense to use inheritance when templates (compile-time polymorphism) is enough?

From: "K. Frank" <kfrank29.c@...>

Date: Sat, 17 Aug 2013 14:37:17 -0700 (PDT)



Hello Group!



Prior to templates, if you wanted to reuse code across

different types, you would use inheritance / polymorphism

where your different types would derive from a common

base type that offered the capabilities needed by your

reusable code.



Now (with templates) if you know at compile time which

objects are of which concrete types you can use templates.

(If the concrete type of an object is only determined at

run time, you still need inheritance.)



This is kind of a soft question, but I'm wondering whether

there are situations where inheritance would still be

preferable, even when concrete types are known at compile

time, and a template solution could have been used.



Assume for this question that the code is special purpose,

so we're not trying to write some general, open-ended

library. That is, the code will be reused across a

smallish number of different types that are all being

designed together, and will not be extended to new types

in the future.



Also assume that efficiency isn't a concern, so that we

don't care about the cost of vtables or the cost (size)

of duplicated template code.



To illustrate my question, below is a simple, do-nothing

example that uses both inheritance and templates for

compile-time polymorphism. printPrintable is an

inheritance-based polymorphic function, while

printHasPrintMe is a generic template function.





Thanks for any thoughts and wisdom.





K. Frank





==========



#include <iostream>



class Printable {

public:

virtual void printMePoly() const = 0;

};



class A : public Printable {

public:

void printMePoly() const { std::cout << "aValue_ = " << aValue_ << std::endl; }

int aValue_ = 13;

};



class B {

public:

void printMeGen() const { std::cout << "bValue_ = " << bValue_ << std::endl; }

int bValue_ = 17;

};



void printPrintable (const Printable& p) {

p.printMePoly();

}



template<typename T> void printHasPrintMe (const T& p) {

p.printMeGen();

}



int main (int argc, char *argv[]) {

A a;

B b;

printPrintable (a);

printHasPrintMe (b);

}



==========







via Usenet Forums - Usenet Search,Free Usenet - comp.lang.c++ http://www.pocketbinaries.com/usenet-forums/showthread.php?67951-When-might-it-make-sense-to-use-inheritance-when-templates-(compile-time-polymorphism)-is-enough&goto=newpost

View all the progranning help forums at:

http://www.pocketbinaries.com/usenet-forums/forumdisplay.php?128-Coding-forums

No comments:

Post a Comment