views:

113

answers:

5

For example concept of Templates in C++ are for comfort as compiler generates some additional code, for your class or for your function, isn't it? So we could live without template by doing some additional (manual work).

What about virtual functions???

Are there any situations where both of them are irreplaceable?

A: 

I have found that it is possible to use polymorphism to achieve the same ends as with templates. However, it does as you suspect take more work. There are other trade offs to consider including performance and maintainability. Those come into play when I make the decision which way to go.

Amardeep
+1  A: 

Of course; before polymorphism was available, and even now in the code of people who do not understand polymorphism, the Giant Switch Statement takes its place.

marijne
The giant switch statement does not allow users of your library to add cases to it. You need a bit more work to fully emulate polymorphism without virtual functions (like implementing your own vtable).
sepp2k
+3  A: 

Yes, we can live without templates by doing more manual work (write the code that the compiler writes, or use void* to remove type specifics).

Yes, we can live without polymorphism by doing more manual work (using switch statements, or storing your own vtable struct).

Are there instances where they're irreplaceable?

The template and polymorphism approaches give you type safety and compiler enforced behavior (e.g. pure virtual) that can't be replaced with some of the manual methods. For example, std::sort is safer to use than qsort which operates on void*. These manual methods can result in lots of code that has to be bug free and maintained. So it depends on your definition of "irreplaceable". With or without these features, these languages are still Turing complete. Theoretically, you can compute anything in a Turing complete language, so we could theoretically replace all languages with BrainF*ck... We just choose not to ;)

Stephen
+2  A: 

It's not quite the same.

Templates effectively generate functions with various signatures at compile time. You could pretty easily copy-paste or code generate all the equivalent methods yourself.

Virtual methods are used to make decisions at runtime, so while they do make programmers' work easier, they rather more difficult to replace. You can't just copy-paste code to simulate virtual functions, but instead you would have to implement almost the same thing yourself, using either a vtable-like table of function pointers or some other alternate approach.

In short virtual functions make it much easier to do some things that would be difficult otherwise, but it's a different set of things than templates affect.

Mark B
A: 

I suspect that you could do everything you would need to do with AND and NOT operations. Everything else is gravy.

dash-tom-bang