Why does this fail to compile with GCC 4.4?
template<typename T>
class A {
public:
void foo () {
}
private:
T x;
};
namespace Ns {
template<typename T>
void do_it (A<T> a) {
a.foo ();
}
};
template<typename T>
void myfun (T x) {
Ns::do_it (x);
}
template<typename T>
class B {
public:
void bar () {
}
private:
T x;
};
namespace Ns {
template<typename T>
void do_it (B<T> b) {
b.bar ();
}
};
int main () {
A<int> a;
B<int> b;
myfun (a);
myfun (b); // error: no matching function call to do_it(B<int>&)
return 0;
}
It must have something to do with the namespace of do_it
. When I remove the namespace around it, it compiles.
Background: I am building a set of functions that may be used with many different container classes. To handle the different interfaces uniformly I use freestanding functions that are overloaded for each of the container classes. These functions shall be put into a namespace to avoid cluttering the global namespace with them.
The definitions for B shall be thought of as coming from a different header file than those for A so reordering is not an option.
You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.
overloading is used when we have various functions , doing SIMILAR operations . template is used when we have various functions , doing IDENTICAL operations .
What is the difference between function overloading and templates? Both function overloading and templates are examples of polymorphism features of OOP. Function overloading is used when multiple functions do quite similar (not identical) operations, templates are used when multiple functions do identical operations.
Function overloading is used when multiple functions do similar operations; templates are used when multiple functions do identical operations. Templates provide an advantage when you want to perform the same action on types that can be different.
The reason is that only ADL is done at the point of the call. Other function lookups are only done in the definition of the myfun
function template.
And at that definition context, only the do_it
overload accepting the A<int>
is declared.
Edit: If you want to have a Standard reference for this, refer to [temp.dep.candidate] and [temp.res]p1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With