简体   繁体   中英

Should I prefer static const variables at class or namespace scope?

Does one have any tangible benefits over the other? I've started using the latter because it doesn't pollute the header file with static const declarations, so it's a bit easier to read. I'm often using these constants in only a couple of member functions.

Class scope:

.hpp

class MyType 
{
private:
    static const std::wstring kFoo;
}

.cpp

const wstring MyType::kFoo(L"foo");
...
void MyType::parse(const wstring& input)
{
    if (input == kFoo) { do1; }  
    ...
}

versus

namespace scope

.cpp

const wstring kFoo(L"foo");
...
void MyType::parse(const wstring& input)
{
    if (input == kFoo) { do1; }  
    ...
}

First of all,

const wstring kFoo(L"foo");

is in global scope, not in a namespace . You can easily wrap that in an anonymous namespace .

namespace
{
   const wstring kFoo(L"foo");
}

Coming to the question of whether it is better to use static member of the class or a member in a namespace , the answer depends on team coding style guidelines as well as personal preferences.

My suggestion would be to put it under the anonymous namespace in the .cpp file. That way, it can remain an implementation detail and the class definition is not polluted by an implementation detail.

PS

Please note that the question static string constants in class vs namespace for constants [c++] addreses the issue but with a difference. In the other post, the user wants to share the static member variable across multiple files. In your post you have explicitly put the static member variable as a private member, and hence not to be shared acrosss files. If that assessment is incorrect, your question is a duplicate of the other question and deserved to be closed as such.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM