简体   繁体   中英

friend function template lookup

According to the standard, friend function declared and defined in class can only be find by ADL. So, I think the following code should compile.

template<int M>
struct test{
    template<int N = 0>
    friend void foo(test){}
};

int main(){
    test<2> t;
    foo(t);// compile
    foo<1>(t);// error
}

However, gcc gives the following error:

main.cpp: In function 'int main()':

main.cpp:10:5: error: 'foo' was not declared in this scope

     foo<1>(t);

     ^~~

Then, I have three problems.

  1. Should template<int N> foo be found according to the standard?
  2. Why foo is found while foo<1> is not?
  3. Is there a workaround besides defining foo outside?

https://en.cppreference.com/w/cpp/language/adl

Although a function call can be resolved through ADL even if ordinary lookup finds nothing, a function call to a function template with explicitly-specified template arguments requires that there is a declaration of the template found by ordinary lookup (otherwise, it is a syntax error to encounter an unknown name followed by a less-than character) (until C++20)

In C++20 mode your code compiles fine, demo: https://gcc.godbolt.org/z/svdfW9drf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM