Is it nice to have variables in the namespace?

I have a set of functions that work with a file. Initially, I ended up in a class, with the only private member being static const std::stringwhich was the name of the file. The user used these functions by creating an object and calling functions from it. However, I think that I will move on to using the namespace, as it is just a collection of functions and makes more sense. The only problem is that I still want to keep this constant string. Will there be something to do in this direction? "

namespace FileHandler {
    // Functions to do stuff with file
    const std::string FILE_NAME;
}

I have a separate implementation file for the namespace, but I wonder if loss of encapsulation can have the file name as a private member in the class, use the namespace instead.

+3
source share
2 answers

You can do similar things, but they will have different semantics.

In a class, a static variable is a declaration, not a definition; it still requires a definition outside the class; Declaring a variable in the namespace is a definition unless you check how externand provide an initializer.

In your case, this does not really matter, since the variables consthave an internal binding by default, so you can easily have several definitions in the program (one per translation unit).

eg.

class Test
{
    static const std::string FILE_NAME;
};

(in some way) is equivalent to:

namespace Test
{
    extern const std::string FILE_NAME;
}

, FILE_NAME . .

namespace Test
{
    const std::string FILE_NAME;
}

, , .

namespace Test
{
    const std::string FILE_NAME = "myfile.txt";
}

Test::FILE_NAME, .

+5

, . , FILE_NAME, . , , . , ? , ? - , .

" ", , ( ) . , .

+2

Source: https://habr.com/ru/post/1728982/


All Articles