Ayrosa
Ayrosa

Reputation: 3513

Why would there be such a requirement for different arguments of the same template parameter?

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.

Upvotes: 0

Views: 92

Answers (2)

Christophe
Christophe

Reputation: 73376

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.

Upvotes: 1

Nard
Nard

Reputation: 1006

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.

Upvotes: 1

Related Questions