← C++ from Scratch Lesson 62 of 62 · 10 XP

Namespaces: namespace

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

When a program grows and includes other people's libraries, names clash: in your code Vector is a vector from physics, while in a library it's something else. A namespace is a surname for names:

namespace physics {
    struct Vector { double x, y; };
    double length(const Vector &v) { return std::hypot(v.x, v.y); }
}

namespace ui {
    struct Vector { int x, y; };       // a different Vector — no conflict
}

physics::Vector v{3, 4};
physics::length(v);                     // 5
  • std:: is the namespace of the standard library, which is why we keep writing std::cout;
  • using std::cout; brings in one name; using namespace std; brings in all the names of std. The latter is convenient in a small program, but in header files and big projects it isn't done: hundreds of names get imported, and your own count or distance suddenly clashes with the standard one;
  • namespaces can be nested: namespace game::ai { … } (C++17), and given aliases: namespace gfx = game::graphics;;
  • an anonymous namespace namespace { … } — the names are visible only in that file (a replacement for static on functions).

Task. Make two namespaces: metric with a function double toBase(double value, const std::string &unit) for km, m, cm (the result in metres), and imperial with the same function for mi, yd, ft, in (1 mi = 1609.344 m, 1 yd = 0.9144 m, 1 ft = 0.3048 m, 1 in = 0.0254 m). Read n lines of number unit and print the length in metres with three decimal places; convert the units from metric with metric::toBase, and the rest with imperial::toBase. At the end, print the sum.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.