简体   繁体   English

没有缺少C ++中的命名空间限定符的错误

[英]no error on lack of namespace qualifiers in C++

I'm working on a small C++ project and ran into some behavior regarding namespaces that looks really weird to me. 我正在研究一个小型C ++项目,并且遇到了一些关于命名空间的行为,这些行为对我来说似乎很奇怪。 I've defined all my classes and functions in a namespace my_project : 我已经在名称空间my_project定义了我的所有类和函数:

// point.hpp:
namespace my_project {
    template <size_t dim> class Point { /* snip */ };
}

// convex_hull.hpp:
namespace my_project {
    std::vector<size_t> convex_hull(const std::vector<Point<2> >& xs);
}

I then went to write a test for everything: 然后,我去为所有内容编写测试:

// convex_hull_test.cpp:

#include <my_project/convex_hull.hpp>

using my_project::Point;

int main()
{
  Point<2> p1 = /* snip */;
  std::vector<Point<2> > xs = {p1, p2, p3, p4, p5, p6};
  std::vector<size_t> hull = convex_hull(xs);

  /* snip */
  return 0;
}

Everything worked just fine, but the next day I looked at it again and realized that I should have written this line instead: 一切都很好,但是第二天我再次看了一下,意识到我应该写这行:

  std::vector<size_t> hull = my_project::convex_hull(xs);

because I never had using my_project::convex_hull anywhere. 因为我从没在任何地方using my_project::convex_hull And yet I don't get any errors for using an undefined symbol when I compile this. 但是,当我编译此符号时,使用未定义符号没有任何错误。 Why can I use this function without a namespace prefix ? 为什么我可以在没有名称空间前缀的情况下使用此功能

This is true for several other functions that I've defined. 对于我定义的其他几个函数也是如此。 When I leave off the line using my_project::Point; 当我using my_project::Point;下线时 I do get errors for using Point without namespace qualification. 我确实在使用没有命名空间限定的Point出错。 Are there different rules for functions, classes or templates about namespace qualification? 关于名称空间限定的功能,类或模板是否有不同的规则? Are the rules the same, indicating that there's something else weird going on? 规则是否相同,表明还有其他奇怪的事情要发生?

I tried this with clang, g++ and icc, on more than one machine. 我在多台计算机上使用clang,g ++和icc进行了尝试。 I tried to construct a minimal test case, but the compiler threw the error that I thought it should in this case. 我试图构造一个最小的测试用例,但是编译器抛出了我认为在这种情况下应该出现的错误。

the type of xs must have been available in the namespace my_project . xs的类型必须在名称空间my_project可用。 What is happening is called Argument-dependent lookup . 发生的事情称为依赖参数的查找

The C++ standard permits it. C ++标准允许它。 If you want to prevent ADL, try 如果要防止ADL,请尝试

std::vector<size_t> hull = (convex_hull)(xs);

Putting parentheses prevents argument-dependent lookup, try that, the compiler should complain. 加上括号可防止依赖于参数的查找,请尝试编译器进行投诉。

EDIT: based on OP's edit 编辑: 基于OP的编辑

See Alan Stokes comment on this answer. 请参阅Alan Stokes对这个答案的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM