I have this example from C++ primer 5th ed:
template <typename T>
int compare(T const& x, T const& y) // in the book const T&
{
cout << "primary template\n"; // I've added print statements
if(std::less<T>()(x, y))
return -1;
if(std::less<T>()(y, x))
return 1;
return 0;
}
template <unsigned N, unsigned M>
int compare(char const(&rArr1)[N], char const(&rArr2)[M])
{
cout << "overload for arrays\n";
return strcmp(rArr1, rArr2);
}
template <>
int compare(char const* const &p1, char const* const &p2)
{
cout << "specilization for char* const\n";
return strcmp(p1, p2);
}
int main()
{
std::cout << compare("Hi", "Mom") << '\n';
}
"Whether we define a particular function as a specialization or as an independent, non-template function can impact function matching. For example, we have defined two versions of our compare function template, one that takes references to array parameters and the other that takes const T&. The fact that we also have a specialization for character pointers has no impact on function matching. When we call compare on a string literal:
compare("hi", "mom");
both function templates are viable and provide an equally good (i.e., exact) match to the call. However, the version with character array parameters is more specialized (§ 16.3, p. 695) and is chosen for this call."
I think the it is incorrect: "compare("hi", "mom"); both templates are viable" because as I see the first version that takes T const&, T const& is not viable because it is instantiated as:
compare(char const(&rArra1)[3], char const(&rArr2)[4]);
In which case sizes are different and as we know the size of an array is a part of its type thus here the two literal strings have two different types thus the Template Argument Deduction will fail thus this instantiation is rejected. it is as if we wrote: compare(5, 0.); // int, double so the compiler cannot deduce a unique type as it is required here.
To confirm what I am saying if I comment out the version taking array types then the code won't compile for that call with two literal strings with different sizes.
What confuses me too is that if I comment out the arrays-type version the code doesn't compile even if I have the third version (taking pointer to character strings)! Is this because of the fact that a Specialization doesn't affect function matching? and what was rejected by a primary template is rejected by all of its specializations?
Please clarify. Thank you!
Related
To prevent any confusion, I very much understand the difference between arrays and pointers, the concept of decay-to-pointer, and the concept of passing an array by reference in C++, etc.
My question here is specifically about the rules used by the compiler to select a function from a set of function overload candidates, when one overload takes an array reference, and the other overload takes a pointer.
For example, suppose we have:
template <class T, std::size_t N>
void foo(const T (&arr)[N])
{
std::cout << "Array-reference overload!" << std::endl;
}
template <class T>
void foo(const T* ptr)
{
std::cout << "Pointer overload!" << std::endl;
}
If we attempt to invoke function template foo() as follows:
const char arr[2] = "A";
foo(arr);
... then my expectation would be that the first overload, the one that takes an array reference, would be selected by the compiler.
However, using GCC 4.9.2, if I compile the above code, I get an error:
test.cpp:28:9: error: call of overloaded ‘foo(const char [2])’ is ambiguous
It's unclear to me why both overloads are considered equally good candidates by the compiler here, since the first overload matches the type exactly, whereas the second overload requires an extra decay-to-pointer step.
Now, I am able to get the above overload working by explicitly using type_traits as follows:
template <class T, std::size_t N>
void foo(const T (&arr)[N])
{
std::cout << "Array-reference overload!" << std::endl;
}
template <class T>
void foo(T ptr, typename std::enable_if<std::is_pointer<T>::value>::type* = 0)
{
std::cout << "Pointer overload!" << std::endl;
}
In this case, the program compiles and the overload that takes an array reference is selected. However, I don't understand why this solution should be necessary. I'd like to understand why the compiler considers a function that requires decay-to-pointer an equally likely overload candidate as the array reference, when the argument passed is very much an array.
the first overload matches the type exactly, whereas the second overload requires an extra decay-to-pointer step.
Because when checking the ranking of implicit conversion sequences in overload resolution, the array-to-pointer conversion is considered as an exact match, thus the 2nd overload has the same rank with the 1st one.
From the standard, $16.3.3.1.1 Standard conversion sequences [over.ics.scs] Table 13 — Conversions
Conversion Category Rank Subclause
No conversions required Identity Exact Match
... ...
Array-to-pointer conversion Lvalue Transformation Exact Match [conv.array]
... ...
It's worth noting that the rank of "No conversions required" (i.e. the case for the 1st overload) is "Exact Match" too.
To study the Overloading of Function Templates, I have wrote two functions:
template <typename T>
void pe16_61_compare(const T&, const T&) {
cout <<"template pe16_61_compare(T, T) called" << endl;
}
// plain functions to handle C-style character strings
void pe16_61_compare(const char*, const char*) {
cout <<"normal func pe16_61_compare(...) called" << endl;;
}
and then I have defined some variables and called the function: pe16_61_compare
const char const_arr1[] = "world", const_arr2[] = "hi";
char ch_arr1[] = "world";
// first call
pe16_61_compare(ch_arr1, const_arr1);
// second call
pe16_61_compare(const_arr1, const_arr2);
the output result is:
template pe16_61_compare(T, T) called
normal func pe16_61_compare(...) called
What confuse me is that the first call invoke the template function. For me, for the first call, both two pe16_61_compare function are viable functions and the have the same rank of conversion (non-const to const and array to pointer), and it is said in this case, the template function should be removed from the set of viable functions.
Could any one tell me why?
Thank you for considering my question!
For the first call, T = char[6] is a better match than the conversion to char const *, so the template wins.
For the second call, no single template parameter can work for arrays, so the non-template overload is the only matching one.
If you say,
pe16_61_compare(static_cast<char const *>(const_arr_1),
static_cast<char const *>(const_arr_2));
then both the template instance and the ordinary function are viable and have the same signature, but as a tie breaker the non-template function wins (i.e. this isn't ambiguous).
The code is:
#include <iostream>
using namespace std;
// compares two objects
template <typename T> void compare(const T&, const T&){
cout<<"T"<<endl;
};
// compares elements in two sequences
template <class U, class V> void compare(U, U, V){
cout<<"UV"<<endl;
};
// plain functions to handle C-style character strings
void compare(const char*, const char*){
cout<<"ordinary"<<endl;
};
int main() {
cout<<"-------------------------char* --------------------------"<< endl;
char* c="a";
char* d="b";
compare(c,d);
cout<<"------------------------- char [2]---------------------------"<< endl;
char e[]= "a";
char f[]="b";
compare(e,f);
system("pause");
}
The result is:
-------------------------char* --------------------------
T
------------------------- char [2]-----------------------
ordinary
And my question is:
Why does compare(c,d) call compare(const T&, const T&) and compare(e,f) call the ordinary function even though the arguments of the two functions are char*s?
It appears that VS2005 may be erroneously treating the e and f variables as const char * types.
Consider the following code:
#include <iostream>
using namespace std;
template <typename T> void compare (const T&, const T&) {
cout << "T: ";
};
template <class U, class V> void compare (U, U, V) {
cout << "UV: ";
};
void compare (const char*, const char*) {
cout << "ordinary: ";
};
int main (void) {
char* c = "a";
char* d = "b";
compare (c,d);
cout << "<- char *\n";
char e[] = "a";
char f[] = "b";
compare (e,f);
cout << "<- char []\n";
const char g[] = "a";
const char h[] = "b";
compare (g,h);
cout << "<- const char []\n";
return 0;
}
which outputs:
T: <- char *
T: <- char []
ordinary: <- const char []
Section 13.3 Overload resolution of C++03 (section numbers appear to be unchanged in C++11 so the same comments apply there) specifies how to select which function is used and I'll try to explain it in (relatively) simple terms, given that the standard is rather a dry read.
Basically, a list of candidate functions is built based on how the function is actually being called (as a member function of an class/object, regular (unadorned) function calls, calls via a pointer and so on).
Then, out of those, a list of viable functions is extracted based on argument counts.
Then, from the viable functions, the best fit function is selected based on the idea of a minimal implicit conversion sequence (see 13.3.3 Best viable function of C++03).
In essence, there is a "cost" for selecting a function from the viable list that is set based on the implicit conversions required for each argument. The cost of selecting the function is the sum of the costs for each individual argument to that function, and the compiler will chose the function with the minimal cost.
If two functions are found with the same cost, the standard states the the compiler should treat it as an error.
So, if you have a function where an implicit conversion happens to one argument, it will be preferred over one where two arguments have to be converted in that same way.
The "cost" can be see in the table below in the Rank column. An exact match has less cost than promotion, which has less cost than conversion.
Rank Conversion
---- ----------
Exact match No conversions required
Lvalue-to-rvalue conversion
Array-to-pointer conversion
Function-to-pointer conversion
Qualification conversion
Promotion Integral promotions
Floating point promotions
Conversion Integral conversion
Floating point conversions
Floating-integral conversions
Pointer conversions
Pointer-to-member conversions
Boolean conversions
In places where the conversion cost is identical for functions F1 and F2 (such as in your case), F1 is considered better if:
F1 is a non-template function and F2 is a function template specialization.
However, that's not the whole story since the template code and non-template code are all exact matches hence you would expect to see the non-template function called in all cases rather than just the third.
That's covered further on in the standard: The answer lies in section 13.3.3.2 Ranking implicit conversion sequences. That section states that an identical rank would result in ambiguity except under certain conditions, one of which is:
Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if (1) S1 is a proper subsequence of S2 (comparing the conversion sequences in the canonical form defined by 13.3.3.1.1, excluding any Lvalue Transformation; the identity conversion sequence is considered to be a subsequence of any non-identity conversion sequence) ...
The conversions for the template version are actually a proper subset (qualification conversion) of the non-template version (qualification AND array-to-pointer conversions), and proper subsets are deemed to have a lower cost.
Hence it prefers the template version in the first two cases. In the third case, the only conversions are array-to-pointer for the non-template version and qualification for the template version, hence there's no subset in either direction, and it prefers the non-template version based on the rule I mentioned above, under the ranking table).
I am confused by how C++ instantiate template. I have a piece of code:
template <class T, int arraySize>
void test1(T (&array)[arraySize])
{
cout << typeid(T).name() << endl;
}
template<class T>
void test2(T &array)
{
cout << typeid(T).name() << endl;
}
int main()
{
int abc[5];
test1(abc);
test2(abc);
return 0;
}
Here are my questions:
1. How does the size of array abc is passed to test1 (the parameter arraySize )?
2. How does C++ compiler determine the type of T in the two templates?
There is no parameter passing in the normal sense, since template parameters are resolved at compile time.
Both arraySize and T are inferred from the type of the array parameter. Since you pass an int[5], arraySize and T become 5 and int, respectively, at compile time.
If, for example, you declared int* abc = new int[5];, your compiler would barf at the point you try to call test1(abc). Apart from a basic type-mismatch, int* doesn't carry enough information to infer the size of the array.
It is called template argument deduction.
The type of abc at call-site is : int(&)[5] which has two info combined: int and 5. And the function template accepts argument of type T(&)[N], but the argument at call-site is, int(&)[5], so the compiler deduces that T is int and N is 5.
Read these:
The C++ Template Argument Deduction (at ACCU)
Template argument deduction (C++ only) (at IBM)
In test1 the compiler creates a template with T[arraySize] being its form.
When you call test1(abc) you are providing an input argument of type int[5] which the template matcher automatically matches.
However, if you were to write
int n=10;
int *abc = new int[n];
test1(abc);
test1<int,n>(abc);
then the compilation would fail and the compiler would claim that it has no template matching the test1(abc) function call or the test1< int,n >(abc) function call.
This is because the size of abc is now dynamically allocated and so the type of abc is a pointer which has a different type and hence no template could be matched to the above two calls.
The following code shows you some types
#include <iostream>
using namespace std;
template <class T> void printName() {cout<<typeid(T).name()<<endl;}
int main()
{
printName<int[2]>(); //type = A2_i
printName<int*>(); //type = Pi
getchar();
return 0;
}
I'd also add to what Nawaz says: the theory is type inference.
Please consider this code:
#include <iostream>
template<typename T>
void f(T x) {
std::cout << sizeof(T) << '\n';
}
int main()
{
int array[27];
f(array);
f<decltype(array)>(array);
}
Editor's Note: the original code used typeof(array), however that is a GCC extension.
This will print
8 (or 4)
108
In the first case, the array obviously decays to a pointer and T becomes int*. In the second case, T is forced to int[27].
Is the order of decay/substitution implementation defined? Is there a more elegant way to force the type to int[27]? Besides using std::vector?
Use the reference type for the parameter
template<typename T> void f(const T& x)
{
std::cout << sizeof(T);
}
in which case the array type will not decay.
Similarly, you can also prevent decay in your original version of f if you explicitly specify the template agument T as a reference-to-array type
f<int (&)[27]>(array);
In your original code sample, forcing the argument T to have the array type (i.e. non-reference array type, by using typeof or by specifying the type explicitly), will not prevent array type decay. While T itself will stand for array type (as you observed), the parameter x will still be declared as a pointer and sizeof x will still evaluate to pointer size.
The behaviour of this code is explained by C++14 [temp.deduct.call]:
Deducing template arguments from a function call
Template argument deduction is done by comparing each function template parameter type (call it P) with the type of the corresponding argument of the call (call it A) as described below
and then below:
If P is not a reference type:
If A is an array type, the pointer type produced by the array-to-pointer standard conversion (4.2) is used in place of A for type deduction;
For the call f(array);, we have A = int[27]. A is an array type. So the deduced type T is int *, according to this last bullet point.
We can see from the qualifier "If P is not a reference type" that this behaviour could perhaps be avoided by making P a reference type. For the code:
template<typename T, size_t N>
void f(T (&x)[N])
the symbol P means T(&)[N], which is a reference type; and it turns out that there are no conversions applied here. T is deduced to int, with the type of x being int(&)[N].
Note that this only applies to function templates where the type is deduced from the argument. The behaviour is covered by separate parts of the specification for explicitly-provided function template parameters, and class templates.
You can also use templates like the following:
template <typename T, std::size_t N>
inline std::size_t number_of_elements(T (&ary)[N]) {
return N;
}
This little trick will cause compile errors if the function is used on a non-array type.
Depending on your use case, you can work around that using references:
template<typename T>
void f(const T& x) {
std::cout << sizeof(T);
}
char a[27];
f(a);
That prints 27, as desired.