When is there an UB because the best overload match was not found by ADL at the point of instantiation?

℡╲_俬逩灬. 提交于 2020-08-02 07:47:32

问题


When a function body is instantiated, dependent function call overload resolution should find the best match in associated namespace through ADL, otherwise the behavior is undefined, [temp.dep.candidate]§1

If the call would be ill-formed or would find a better match had the lookup within the associated namespaces considered all the function declarations with external linkage introduced in those namespaces in all translation units, not just considering those declarations found in the template definition and template instantiation contexts, then the program has undefined behavior.

For exemple:

struct A {
    friend void f(A a){};
};

struct B : A {};

template <class T> 
void g (T a) {
    f(a);
}

void h(B b){
    g(b);//undefined behavior (UB)
}
 //TU2.cpp
 //...
void f(B){}

I have 2 doubts about which functions could be one of all the function declarations with external linkage introduced in those namespaces

Question 1

Does inline friend function considered to be introduced in the enclosing namespace?

Exemple:

struct A {
    friend void f(A a){};
};

struct B : A {};

template <class T> 
void g (T a) {
    f(a);
}

void h(B b){
    g(b);//undefined behavior ??
}
//TU2.cpp
//....
struct C {
   operator B();
   friend void f(B){}
   };

Question 2

Could function template specialization also trigger this undefined behavior? (Potentialy instantiated or instantiated function template specialization)

Exemple:

struct A {
    friend void f(A a){};
};

struct B : A {};

template <class T> 
void g (T a) {
    f(a);
}

void h(B b){
    g(b);//undefined behavior ??
}
//TU2.cpp
//...
template <class T> void f(T){}

// optionaly also with:
// template void f(B);

来源:https://stackoverflow.com/questions/63105174/when-is-there-an-ub-because-the-best-overload-match-was-not-found-by-adl-at-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!