Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 524
cqdjyy01234 Avatar asked Jun 20 '16 02:06

cqdjyy01234


1 Answers

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

like image 64
Fedor Avatar answered Oct 03 '22 08:10

Fedor