lundi 26 octobre 2015

When I should use my own namespaces?

First of all, I can't understand structure of C++ standard library or std. For example, "Hello, world!" programm looks like this:

#include <iostream>

int main() {
    std::cout << "Hello, world!" << std::endl;
}

More complex program for generating random numbers and execution time assesment looks like this:

#include <iostream>
#include <random>
#include <chrono>
#include <time.h>

int main() {
    std::chrono::time_point<std::chrono::system_clock> start, end;
    std::tr1::default_random_engine eng(static_cast<unsigned int>(time(NULL)));
    std::tr1::uniform_int<int> unif(0, 99);

    start = std::chrono::system_clock::now();

    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            std::cout << unif(eng) << " ";
        }

        std::cout << std::endl;
    }

    end = std::chrono::system_clock::now();

    int elapsed_milliseconds = std::chrono::duration_cast<std::chrono::milliseconds> (end - start).count();

    std::cout << "Elapsed time: " << elapsed_milliseconds << "ms" << std::endl;

    std::cin.get();
    return 0;
}

By my opinion code like this:

std::tr1::uniform_int<int> unif(0, 99);

or this:

std::chrono::time_point<std::chrono::system_clock> start, end;

looks very ugly. Of course I can use something like this:

using namespace std;
using namespace std::tr1;
using namespace std::chrono;

But this code may cause some problems: Why is "using namespace std;" considered bad practice?

I can't understand the reason for creating nested namespaces in standrad library. Is it only one reason conected with name function conflicts? Or something else?

And for my own project when I should use my own namespaces?

Aucun commentaire:

Enregistrer un commentaire