← 講座に戻る: Modern C++ from scratch

Namespaces and week 3 review

動画は近日公開

As a program grows, repeated names appear: two functions called print, two classes called Item. Namespaces group declarations under a prefix to avoid clashes. You already use them without knowing: std is the namespace of the standard library, which is why you write std::cout and std::string. In this lesson you learn to create your own, to use them wisely, and we review the week with a program that combines functions, references and namespaces.

Creating and using a namespace

It is declared with the word namespace and a name, followed by a block with braces. To use something inside, you write the name, the scope resolution operator :: and the member: geometry::area(3.0). You can reopen the same namespace in different places to add more things. Namespaces can nest, and since C++17 you write it compactly: namespace shop::pricing { ... }. Inside the namespace itself you do not need the prefix to refer to its members.

cpp
#include <iostream>

namespace circle {
    constexpr double kPi = 3.14159265358979;
    double area(double r) { return kPi * r * r; }
}

namespace square {
    double area(double side) { return side * side; }   // same name, no clash
}

namespace shop::pricing {                              // C++17 nested form
    double withVat(double net) { return net * 1.21; }
}

int main() {
    std::cout << circle::area(1.0) << '\n';
    std::cout << square::area(3.0) << '\n';
    std::cout << shop::pricing::withVat(100.0) << '\n';
    return 0;
}

using: when yes and when no

using namespace std; imports everything from std and saves typing the prefix. In short examples it looks convenient, but in real programs it is a bad idea: it can cause name clashes and ambiguities that are hard to understand, and in a header file it pollutes everyone who includes it. The recommended alternative is a targeted using declaration inside a function, using std::cout;, or simply writing the prefix, which also reminds you where each thing comes from. You can also define an alias: namespace fs = std::filesystem; is useful with long names.

Review: a week 3 program

The following program uses everything from this week: small functions with clear names, overloading, const and non-const reference parameters, a default argument and its own namespace to group text utilities. Read it, run it and change it: alter the test data and add a new function inside the namespace.

cpp
#include <iostream>
#include <string>

namespace textutil {

    std::string repeat(const std::string& s, int times = 2) {
        std::string out;
        for (int i = 0; i < times; ++i) {
            out += s;
        }
        return out;
    }

    void trimTrailingSpaces(std::string& s) {
        while (!s.empty() && s.back() == ' ') {
            s.pop_back();
        }
    }

    int count(const std::string& s, char c) {
        int n{0};
        for (char ch : s) {
            if (ch == c) {
                ++n;
            }
        }
        return n;
    }

    int count(const std::string& s, const std::string& part) {   // overload
        int n{0};
        std::size_t pos = s.find(part);
        while (pos != std::string::npos) {
            ++n;
            pos = s.find(part, pos + part.size());
        }
        return n;
    }

}

int main() {
    std::string text = "banana   ";
    textutil::trimTrailingSpaces(text);
    std::cout << '[' << text << "]\n";
    std::cout << textutil::repeat("ab") << ' ' << textutil::repeat("ab", 3) << '\n';
    std::cout << textutil::count(text, 'a') << ' ' << textutil::count(text, "an") << '\n';
    return 0;
}

A habit worth fixing from now on: inside a namespace you can define helper functions used only in one .cpp file, and so that they do not clash with those in other files they are placed in an anonymous namespace (namespace { ... }). Everything inside has internal linkage: it is invisible outside that translation unit. It is the modern form of what C did with static, and it avoids multiple-definition errors when linking projects with several files.

Practical summary of the week: use explicit std:: in header files and avoid using namespace std; in them; group your own functions in a namespace named after the project; and pass by const reference whatever you will not modify. With those three rules you avoid most name clashes and unnecessary copies.

理解度チェック

問題 1 / 6

What happens with void f(int& x) when you call f(n)?

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →