调用struct中定义的friend函数需要正向声明吗? [英] Calling friend function defined in struct requires forward declaration?

查看:103
本文介绍了调用struct中定义的friend函数需要正向声明吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读Karlsson的超越C ++标准时,作者在 class reference_counted 类的正文中定义了朋友功能 intrusive_ptr_add_ref (请参见第36页).该函数会在适当的时候使用Argument Dependent Lookup自动调用.

While reading Karlsson's Beyond the C++ Standard the author defined the friend function intrusive_ptr_add_ref in the body of class reference_counted (see pg 36). That function is called automatically using Argument Dependent Lookup at the proper time.

我从来没有见过在类的主体中定义的好友函数,而是四处探索,发现如果不使用ADL查找,gcc 4.4.3需要进行前向声明.实际上,如果没有该前向声明,似乎没有办法引用 adl_no .这是C ++标准的一部分,还是gcc的产物? (我没有Windows框,因此无法尝试VC.)

Never having seen friend functions defined in the body of a class, I played around and discovered that gcc 4.4.3 requires a forward declaration if not using ADL lookup. In fact, there seems to be no way to reference adl_no without that forward declaration. Is this part of the C++ standard or is it an artifact of gcc? (I don't have Windows box so cannot try VC).

#include <cstdlib>
#include <iostream>


namespace {
    void adl_no();        // Remove this and it won't compile with gcc

    struct Q {
        friend void adl_yes(const Q&) {
            std::cout << "adl_yes" << std::endl;
        }

        friend void adl_no() {
            std::cout << "adl_NO" << std::endl;
        }
    };
}


int main(int argc, char** argv)
{
    adl_yes(Q());
    adl_no();

    return EXIT_SUCCESS;
}

推荐答案

是的,此行为是标准行为.该标准的相关部分是7.3.1.2 [namespace.memdef]第3段:

Yes, this behaviour is standard. The relevant part of the standard is 7.3.1.2 [namespace.memdef] para 3:

如果非本地类中的friend声明首先声明了一个类或函数,则该朋友类或函数是最内部封闭的命名空间的成员.直到在该名称空间范围中提供了匹配的声明,才可以通过简单的名称查找来找到朋友的名字.如果调用了朋友函数,则可以通过名称查找来找到其名称,该名称查找考虑了与函数自变量类型(3.4.2)相关的名称空间和类中的函数. ADL].

If a friend declaration in a non-local class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by simple name lookup until a matching declaration is provided in that namespace scope [...]. If a friend function is called, its name may be found by the name lookup that considers function from namespaces and classes associated with the types of the function arguments (3.4.2) [i.e. ADL].

这篇关于调用struct中定义的friend函数需要正向声明吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆