【问题标题】:friend function template lookup朋友功能模板查找
【发布时间】:2016-10-21 04:41:45
【问题描述】:

按照标准,类中声明和定义的友元函数只能通过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&lt;int N&gt; foo应该按标准找吗?
  2. 为什么找到foo 而找不到foo&lt;1&gt;
  3. 除了在外面定义foo之外,有没有变通的办法?

【问题讨论】:

  • 它不适用于 clang 3.8 但它适用于 GCC 5.3.1
  • @JohanBoule 不适用于 coliru.stacked-crooked.com 上的 g++
  • 你到底想在代码中做什么?
  • @PurityLake 它什么都不做。但它的作用与我的问题无关。

标签: c++ argument-dependent-lookup friend-function function-templates


【解决方案1】:

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

虽然函数调用可以通过 ADL 解析,即使普通查找什么也没找到,但对具有显式指定模板参数的函数模板的函数调用需要有普通查找找到的模板的声明(否则,它是遇到未知名称后跟小于字符的语法错误) (直到 C++20)

在 C++20 模式下,您的代码编译良好,演示:https://gcc.godbolt.org/z/svdfW9drf

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 2015-09-29
    相关资源
    最近更新 更多