#include <iostream>
#include <vector>
using namespace std;
template <typename nameOfTheVariableTypeA,
typename nameOfTheVariableTypeB> nameOfTheVariableTypeB functionX
(nameOfTheVariableTypeA argA,
(nameOfTheVariableTypeB argB)
{
nameOfTheVariableTypeA tempArgA;
nameOfTheVariableTypeB tempArgB;
argA.push_back(22);
tempArgA = argA;
cout << "\ntempArgA: " << tempArgA[0] << "\n";
tempArgB = argB;
cout << "\ntempArgB: " << tempArgB << "\n";
return tempArgB;
}
int main ()
{
functionX (12, 12.4567);
vector <int> f;
functionX (f, 12.4567);
return 0;
}
From a template book:
An attempt to instantiate a template for a type that doesn't support all the operations used within it will result in a compile-time error.
The error I received for the above code is:
-
error: request for member ‘push_back’ in ‘argA’, which is of non-class type ‘int’ -
error: subscripted value is neither array nor pointer
What’s the point that I am missing?
First off, there’s a superfluous parenthesis:
Assuming that’s just a typo, let’s take a look the first call to
functionX():Now, template functions require that all template parameters be specified before you can call them. But in certain cases the compiler can deduce the required type for
nameOfTheVariableTypeAandnameOfTheVariableTypeBfor the function call to work.In this case,
12is an integer literal, so it has typeint.12.4567is a floating-point literal, so it has typedouble. Thus, withinfunctionX(),nameOfTheVariableTypeAis of typeintandnameOfTheVariableTypeBis of typedouble.Now that all the template parameters have been specified (in this case, deduced), the compiler can instantiate the template function. That is, the compiler creates a function that looks like this:
It’s as though the compiler simply substituted
nameOfTheVariableTypeAandnameOfTheVariableTypeBwith the deduced types. Clearly, the argumentargAand variabletempArgAhas typeint. You get the first error becauseintdoesn’t have a class member function calledpush_back(). It’s the same reason why this won’t work:You also get the second error because the subscript operator
[]is not defined forints. Again, it’s the same reason why this won’t work:Note that this kind of information can be gleaned from the compiler errors themselves. Make sure you read them!