开发者

Overloading function templates in namespaces

开发者 https://www.devze.com 2023-02-26 05:59 出处:网络
Why does this fail to compile with GCC 4.4? template<typename T> class A { public: void foo () { } private:

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消