Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why some Boost functions don't need prefixing with namespace

Consider this code (or the live example):

#include <iostream>

#include <boost/graph/adjacency_list.hpp>
#include <boost/range/iterator_range.hpp>

using std::cout;

int main() {
  boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> g;

  add_edge(0, 1, g);
  add_edge(1, 2, g);

  for(auto v : make_iterator_range(vertices(g))) {
    cout << v << " has " << degree(v, g) << " neighbor(s): ";
    for(auto w : make_iterator_range(adjacent_vertices(v, g))) cout << w << ' ';
    cout << '\n';
  }
  return 0;
}

Why do functions add_edge, make_iterator_range, vertices, degree and adjacent_vertices that come from the Boost library work without the boost:: namespace prefix?

What is most puzzling to me is that depending on the situation, the prefix is actually needed sometimes. Here is an example, when using a different graph structure results in a compilation error that can be fixed by prefixing boost::make_iterator_range.

I looked a bit around the BGL documentation, but didn't find anything regarding this issue. Is it my fault or are some BGL headers polluting the global namespace? Is this by design or is this a bug?

like image 738
arekolek Avatar asked Nov 01 '15 12:11

arekolek


People also ask

When should you use namespace?

Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

Should I always use namespace C++?

Answer: If you ever want to overload the new, placement new, or delete functions you're going to want to do them in a namespace. No one wants to be forced to use your version of new if they don't require the things you require.

Do I need to use namespaces?

Under no circumstances must you use namespace std within a header file, that's a recipe for errors straight away. Do use namespaces, they will make your code so much more sorted out. And finally if you're going to use namespace STD, don't write functions that have the same name to functions within the standard library.


1 Answers

It is not related to boost but to any namespace.

With argument-dependent lookup (ADL), namespaces from the argument are added to the search of overloads.

So for example:

add_edge(0, 1, g);

g is from namespace boost, so we look for add_edge also in namespace boost.

like image 145
Jarod42 Avatar answered Mar 16 '23 16:03

Jarod42