简体   繁体   中英

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. I've defined all my classes and functions in a namespace 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. 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; I do get errors for using Point without namespace qualification. 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. 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 . What is happening is called Argument-dependent lookup .

The C++ standard permits it. If you want to prevent ADL, try

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

See Alan Stokes comment on this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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