加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

什么是C名称查找在这里? (&GCC对吗?)

发布时间:2020-12-16 07:49:30 所属栏目:百科 来源:网络整理
导读:我在一些生产代码中遇到了一个问题,我将其最小化到以下测试用例: templatetypename Tvoid intermediate(T t){ func(t); // line 4 ("func not declared in this scope")}namespace ns { struct type {};}void func(ns::type const p); // line 11 ("declare
我在一些生产代码中遇到了一个问题,我将其最小化到以下测试用例:
template<typename T>
void intermediate(T t)
{
    func(t); // line 4 ("func not declared in this scope")
}

namespace ns {
    struct type {};
}

void func(ns::type const & p); // line 11 ("declared here,later")

void foo(ns::type exit_node)
{
    intermediate(exit_node);  // line 15 ("required from here")
}

GCC 4.5编译这个罚款.无论是否使用-std = c 11,4.7和4.9都会生成如下消息:

test.cpp: In instantiation of ‘void intermediate(T) [with T = ns::type]’:
test.cpp:15:27:   required from here
test.cpp:4:5: error: ‘func’ was not declared in this scope,and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]
test.cpp:11:6: note: ‘void func(const ns::type&)’ declared here,later in the translation unit

以下三件事情将导致文件成功编译:

>将func(ns :: type)移动到ns命名空间中(允许ADL在ns中找到它)
>将类型移动到全局命名空间(允许ADL在:)中找到它:
摆脱中间,直接从foo调用func

那么…这里发生了什么?海湾合作委员会拒绝这个方案是否合法?为什么在第三个变体(通过foo直接调用func)找到func,但是在实例化的时候,原始变体中不合格查找找不到func?

解决方法

一般规则是,任何不在模板定义上下文中的内容只能通过ADL来获取.换句话说,正常的不合格查找仅在模板定义上下文中执行.

因为在定义中间语句时没有声明func,并且func不在与ns :: type相关联的命名空间中,所以代码形式不正确.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读