I'm trying to understand how the overload selection rules result in the following (unintuitive) behavior. When I have the following functions:
#include <iostream>
// Overload 1
template<class T>
void write(T data)
{
std::cout << "Called write(T data)" << std::endl;
}
// Overload 2
template<class T, class ...U>
void write(T&& obj, U&&... objs)
{
std::cout << "Called write(T&& obj, U&&... objs)" << std::endl;
}
int main(int, char**)
{
int j = 0;
write(j);
return 0;
}
The void write(T data)
overload (Overload 1) is selected. I think that makes sense to me: the candidates for overload selection are void write<T>(T)
T = int
and void write<T,U>(T&)
T = int, U = <>
. Both write(T)
and write(T&)
would be equally specialized, but Overload 2 has an empty parameter pack so Overload 1 is selected. However, if I add a third overload:
#include <iostream>
// Overload 0
void write(const int& data)
{
std::cout << "Called write(const int& data)" << std::endl;
}
// Overload 1
template<class T>
void write(T data)
{
std::cout << "Called write(T data)" << std::endl;
}
// Overload 2
template<class T, class ...U>
void write(T&& obj, U&&... objs)
{
std::cout << "Called write(T&& obj, U&&... objs)" << std::endl;
}
int main(int, char**)
{
int j = 0;
write(j);
return 0;
}
Then all of a sudden void write(T&& obj, U&&... objs)
(Overload 2) is what gets called. Why does adding an overload that doesn't get selected change which overload actually does get selected?
If the only candidates were void write<T,U>(T&)
T = int, U = <>
and void write(const int&)
I understand why void write<T,U>(T&)
would be selected, so perhaps something about adding the extra overload prevents void write(T data)
from participating on overload selection? If so why?
Since this seems to be compiler specific behavior this was observed on gcc 7.3.0.
Some more interesting behavior:
If the functions are reordered such that the new overload is placed between the original two (i.e. Overload 1, then Overload 0, then Overload 2) then gcc rejects it with call of overloaded ‘write(int&)’ is ambiguous
. If the functions are reordered such that the new overload is last (i.e. Overload 1, then Overload 2, then Overload 0) then write(const int& data)
is selected.
Called write(T data)