friend function template lookup
Asked Answered
P

1

9

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?
Photoluminescence answered 20/6, 2016 at 2:19 Comment(4)
It does not work on clang 3.8 but it works on GCC 5.3.1Oil
@JohanBoule Not work with g++ on coliru.stacked-crooked.comPhotoluminescence
What exactly are you trying to do in the code?Dimitry
@Dimitry It does nothing. But what it does has nothing to do with my problems.Photoluminescence
N
3

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

Nutbrown answered 4/12, 2021 at 17:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.