朋友功能模板查找

friend function template lookup

本文关键字:查找 功能 朋友      更新时间:2023-10-16

根据标准,只能通过ADL找到类声明和定义的朋友函数。因此,我认为以下代码应该编译。

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
}

但是,GCC给出以下错误:

main.cpp: In function 'int main()':
main.cpp:10:5: error: 'foo' was not declared in this scope
     foo<1>(t);
     ^~~

然后,我有三个问题。

  1. 应该根据标准找到template<int N> foo吗?
  2. 为什么在foo<1>没有的情况下找到foo
  3. 除了在外面定义foo外,还有解决方法吗?

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

虽然可以通过ADL解决函数调用,即使普通查找一无所获,但使用明确指定的模板参数对函数模板进行函数调用要求,需要普通查找的模板声明(否则,它是语法错误会遇到一个未知名称,然后是一个不太明显的字符)(直到C 20)

在C 20模式中,您的代码编译罚款,演示:https://gcc.godbolt.org/z/svdfw9drf