c++ - Why is the template function ambiguous? -
when compile code error saying
call of overloaded
swap(int&, int&)
ambiguous
but i've written 1 swap function here.
can tell me why function ambiguous , changes need run program correctly?
using namespace std; template <class t> void swap(t& x, t& y) { t temp; temp = x; x = y; y = temp; } int main() { int a, b; cout << "enter 2 elements: "; cin >> a; cin >> b; swap(a, b); cout << "a "<<a << '\t'<<"b " << b << std::endl; return 0; }
why swapping function overloaded though has only swap function?
you should use
::swap(a,b); //use 1 in global namespace, 1 defined
if call 1 defined. since std
has defined swap
function template, compiler search std namespace
if not use ::
.
more specifically, parameter a
, b
of type int
, defined in std namespace
, when compiler searches swap
, find both versions: 1 in std namespace
, other defined in global namespace
. need tell compiler 1 should use explicitly, otherwise, lead ambiguity.
Comments
Post a Comment