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

前端之家收集整理的这篇文章主要介绍了什么是C名称查找在这里? (&GCC对吗?)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在一些生产代码中遇到了一个问题,我将其最小化到以下测试用例:
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相关联的命名空间中,所以代码形式不正确.

原文链接:https://www.f2er.com/c/115322.html

猜你在找的C&C++相关文章