Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading function templates in namespaces

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.

like image 723
Roland W Avatar asked Apr 18 '11 17:04

Roland W


People also ask

Can we have overloading of function templates?

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.

What is the relationship between function templates and overloading?

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 templates and overloading?

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.

What is the main difference between function overloading and function template?

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.


1 Answers

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.

like image 92
Johannes Schaub - litb Avatar answered Nov 18 '22 10:11

Johannes Schaub - litb