0

In page 671 of his new book Mr Stroustrup wrote the following sentence:

Note that there is no requirement that different arguments for the same template parameter should be related by inheritance.

I can understand what the author wrote, but I can't understand the reason why he inserted this comment in the text. I think I'm missing something here, but I don't know exactly what.

Ayrosa
  • 3,385
  • 1
  • 18
  • 29

2 Answers2

1

When introducing the concept of templates, he tries to make clear that its not some kind of polymoprhism.

Before template were invented and added to C++ you could write generic code only using inheritance (or multilple inheritance).

Another concept that Mr.Stroustrup certainly want the reader not to confuse with templates is interfaces. In the java comunity for example this is a very popular technique and many books abot OOP explain this concept. Interfaces allow you to use some kind of generic code with a class, at the condition that the class is defined to implement (not inherit) a specific interface. All classes using the interface must be related to it. It's not strictly speaking inheritance, but it's a kind of substitute to multiple inheritance.

Templates can be used with any object or class without its type being related in advance to anything in common.

Christophe
  • 68,716
  • 7
  • 72
  • 138
  • Could you give me some references regarding your second paragraph above? – Ayrosa Dec 13 '14 at 10:58
  • 1
    I'm satisfied with your answer. I would just mention [this answer](http://stackoverflow.com/a/1039904/411165) which also gave me some insight into the issue I've raised. Thanks (+1). – Ayrosa Dec 13 '14 at 11:30
  • It's primarily my own experience, when I started with ATT C++2.0, when I had to implement things like this: http://msdn.microsoft.com/en-us/library/6td5yws2.aspx . Apparently it's even mentioned in some books as this SO question suggests: http://stackoverflow.com/questions/23939939/multiple-inheritance-and-generic-program – Christophe Dec 13 '14 at 11:34
1

The answer is simple if we look at the use case of templates from the perspective of someone who is totally new to the concept of templates.

int i;
double d;
char c;

print(&i); //prints an integer
print(&d); //prints a double
print(&c); //prints a char

From the perspective of someone who does not understand C++ templates, he/she would assume that the prototype of print looks something like this.

print(SomeBaseType* pdata);
OR
print(void* pdata);

However, what happens with templates is with a function template such as

template <typename T>
print(T* pdata);

for the above use case, the compiler generates three functions during compile-time

print(int* pdata);
print(double* pdata);
print(char* pdata);

and through function overload resolution, the right function gets called.

Thank you for reading.

Disclaimer: A print function might not be the best example.

Nard
  • 1,006
  • 7
  • 8