C++ Namespace versioning - c++

In C++ its possible to do the following for namespace versioning
First version:
namespace A__v1 {
class X ...
class Y ...
class Z ...
}
namespace A = A__v1
Second version (where the X class is changed):
namespace A__v1 {
class X ...
class Y ...
class Z ...
}
namespace A__v2 {
class X ...
using A__v1::Y;
using A__v1::Z;
}
namespace A = A__v2
What i would like to know is, is it worth the effort? Does this really add any advantage to your application/library when changing the internals of a namespace?

I actually like the non-macro way of handling this, it allows one build of the library to serve many versions. This will inevitably increase library size (due to more versions of some classes all being present) but there is one caveat though: the compiler will most likely report the full namespace qualification of the classes, making the user of your library, who doesn't know about your non-standard versioning scheme very confused.
On second thought, I also don't see the use of supplying two versions of the same thing in one library build, except if there are different CPUs/architectures involved, but I don't think that's what you're getting at. Keeping old versions of classes around is not smart, people will never switch to the newer ones if they don't need to, and if something (half-internal) gets deprecated, you'll have removed something that was "part of the library" so to speak.

It's a nice trick and quite useful but there are some problems to be aware of. Mostly, you can't specialize a template using the name A for the namespace.
C++0X have inline namespaces which was designed to handle this better.

the library can be tricky for the programers who will use that namespace, maybe it's better to use separate namespaces independently to make the difference.

Related

C++, namespace best practice

My project is divided into modules and they all share a similar structure, instead of writing classes like EntityHandler and InputHandler, I'd like to use namespaces and do Input::Handler and Entity::Handler. Now this all seems good to me, but those namespaces are also nested inside one more namespace which also have a Handler class!
Some people said that this is bad practice and could be confusing, but as part of my style I never use the using <namespace>; keyword so it will always look explicit. Do you think this would be good practice, and if not can you tell me where this could come back to bite me down the line?
I'm sorry if this has been asked before, the places I looked didn't give good explanations as to why or why not to do this!
I think it is better to fully qualify namespace without using because it allow to get rid of some mistakes when reading and/or compiling code. In many tutorials it is recommended to use fully qualify namespace i.e. void doSome (std::vector& data) in function declaration instead of placing using namespace std + doSome (vector& data) . It is good practice to fully qualify namespace because it allow to reduce type resolve ambiguity errors on a compilation stage. Consider following example:
class A {
private:
Super::Handler* _handlerOne;
Super::Entity::Handler* _handlerTwo;
};
It would be hard to do the same when you will be use using:
using namespace Super;
using namespace Super::Handler;
class A {
private:
Handler* _handlerOne; // What type compiler place here ??? , we don't know ...
Handler* _handlerTwo; // What type compiler place here ??? , we don't know ...
};
Less ambiguities - better code.

Why is Microsoft using struct rather than class in new code?

So normally I wouldn't ask a question like this because it seems like it could be opinion based or start some sort of verbal war on coding practices, but I think there might be a technical reason here that I don't understand.
I was looking over the code in the header files for vcpkg (a library packing manager that Microsoft is creating and is "new" code) because reading code generally is a good way to learn things you didn't know.
The first thing I noticed was the use of using rather than typedef.
Snippet from 'https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/parse.h'
template<class P>
using ParseExpected = ExpectedT<std::unique_ptr<P>, std::unique_ptr<ParseControlErrorInfo>>;
I haven't personally used using this way before and an answer from: What is the difference between 'typedef' and 'using' in C++11?. Essentially, using is the new way to do it, and the benefit is that it can use templates. So Microsoft had a good reason to use using instead of typedef.
Looking at 'https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/commands.h' I noticed that they did not use any classes. Instead it was only namespaces with a function or so in them. ie:
namespace vcpkg::Commands
{
namespace BuildExternal
{
void perform_and_exit(const VcpkgCmdArguments& args, const VcpkgPaths& paths, const Triplet& default_triplet);
}
}
I'm guessing that part of this is that the calling syntax looks essentially just like a static member function in a class, so the code performs the same but maybe saves some overhead by being a namespace instead of a class. (If anyone has any ideas on this too that would be great.)
Now the main point of all this. Why is Microsoft using structs instead of classes in their namespaces?
Snippet from 'https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/parse.h':
namespace vcpkg::Parse
{
/* ... Code I'm excluding for brevity ... */
struct ParagraphParser
{
ParagraphParser(RawParagraph&& fields) : fields(std::move(fields)) {}
void required_field(const std::string& fieldname, std::string& out);
std::string optional_field(const std::string& fieldname) const;
std::unique_ptr<ParseControlErrorInfo> error_info(const std::string& name) const;
private:
RawParagraph&& fields;
std::vector<std::string> missing_fields;
};
}
Searching stackoverflow, I found an old question: Why Microsoft uses a struct for directX library instead of a class?
Which the answers were essentially, you don't have to declare things as public as default and a comment way at the bottom saying that it was old code.
If vcpkg was old code I would be completely satisfied, however, this is new code. Is it just some style they have that is a carry over (but using vs typedef isn't)? Or is it to save a line of code (public:)? Or is there some sort of overhead benefit? Or some other thing I haven't considered at all?
The only differences between struct and class are:
the default member access (public vs private) and
the default inheritance if you inherit from the type (public inheritance vs private inheritance).
The end result of 1 will be the same once the author has finished adding public:/private: to the type. 2 you can easily control yourself by being explicit when you inherit, rather than rely on the default. It's hardly a big deal and doesn't really matter.
As to why Microsoft uses struct rather than class in their code, you will have to ask some Microsoft people.
Regarding the free functions vs static functions, I don't think there is any overhead in this with classes (I haven't measured this at all, I would just think that most compiler would recognize that the class is basically just a namespace for the function). The thing is just: You don't need a class.
Using a class with only static functions is basically abusing the class as a namespace. So if you are only doing that, then be explicit about it and just use a namespace. Having a class there would only be confusing since you would think that maybe there could be some state here and just see that there is non when you see that the function in the class is static.
This is especially relevant if this is used a bit wrongly. Imagine someone instantiates a class A a with static member function f to call a.f(). It is no problem regarding performance, since the construction is a no-op and it will pretty much be equivalent to A::f(). But for the reader it seems like there is some kind of state involved and that is just confusing.
Regarding the other two: using is just superior to typedef throught being able to use templates and is (IMO) better readable. The struct vs class issue is just something over what has the better defaults, its not a big difference, but most often, what you want is what a struct does, so there is no reason to use a class.
To be (more) compatible with C
To avoid making everything public by using the public: keyword, since that all COM objects for example have only public member functions.

C++: Refactoring managing namespaces

I am refactoring a widely used class. Given how widely it is used, my intend is to create a version 2 of the class. I will keeping the interfaces same/similar [I am forced to make some changes, otherwise it will become ugly with new changes] so that switching from old class to new class becomes easy. And we can switch applications using the old class to new class one by one.
Now I am not sure how to manage name / namespace in this case.
Eg:
Currently, lets say, the class is under a namespace 'app'
namespace app {
class Important {
...
};
}
I would like to keep the class name same or very similar so that the meaning is clear.
namespace app {
// This looks okay (conveys the meaning), but is ugly.
class Important2 {
...
};
}
namespace app {
namespace v2 {
// I think this will be confusing. It will given a feeling that the v2
// applies to app namespace. There are lot of classes under 'app'
// namespace which are not changed.
class Important {
};
}
};
Is there a better approach?
Thanks!
I think the best solution to your problem is to used the gof factory design pattern, where you have an interface and a number of implementations for example Important, Important2 etc.
You could then tell your consumer that you will be deprecating Important soon but a compiler warning
You could resolve via simple namespace alias.
A sample could be in this answer https://stackoverflow.com/a/41420638/781933, for a switch on/off approach (driving migrations on a per-project base).
If instead you have to go through intermediate compositions rather than a complete replacement you could adopt intermediate solutions with compositions and inline namespaces.
You can find a specific example of version management via namespacing in the Stroustrup's The C++ Programming Language.

Use namespaces or prepend vendor's name when naming classes?

Currently I'm working on the project that is just born. Previous developers used to name each class prepending a shorten vendor name i.e. CssMainWindow. (Css stands for Cool Software Solutions).
My question is: Shouldn't namespaces be used here? Then names of classes become much nicer.
That is:
namespace Css {
class MainWindow {
//...
};
}
What are the (ad|dis)vantages of both methods?
Appending a prefix makes the class name longer and it takes longer to type. That's the only disadvantage I can think of.
Using namespaces.... well you can just put
using namespace Css;
at the beginning of your files and file origin will be lost along with that.
I guess in the end it's up to the developer. There are 2 reasons I can think of why someone would want to identify classes:
1) For a sense of ownership. In that case, appending a prefix is, IMO, the way to go. People using your code will know it's YOUR code :).
2) For grouping classes together - in which case a namespace makes more sense.
It would depend. If your vendor-specific classes include some things like e.g.
tuple, make_tuple
string, vector
you may well wish to prefix, so as to prevent ugly ADL clashes1, and general inconvenience when people are expected to be using using namespace XXX. Popular libraries already have used that strategy (XString (Xalan), QString (Qt), CString (MFC) etc)
1 What are the pitfalls of ADL?
My suggestion: Always use namespace!
I will show several advantages of namespace:
// MainWindow.h
namespace Css {
class MainWindow {
// ...
};
};
// Other.cpp
namespace Css {
// An advantage is you don't always need to write the namespace explicitly.
MainWindow* window; // Not Css::MainWindow or CssMainWindow.
}
// In some cpp files
using namespace Css; // Never do this in header file or it will cause name pollution.
MainWindow* window; // You don't need to write Css:: in the whole file.
I can't recall any disadvantage of using namespace.
First things first.
Whatever the final choice, you should avoid as much as possible writing anything in the global namespace. You risk to face name clashes there. Therefore, your software should always be in a namespace of its own, and it's better if the name differs from those used in the libraries you depend of (reminder std is reserved already).
Once you have this namespace, then you normally don't need prefixing any longer. At least, not with the project name.
However it is mostly a matter of taste, and I have seen argued in the past that it made it easier to immediately identify where the class came from in the absence of IDE... I personally consider it and outdated habit inherited from C.

c++ Namespace headaches

Okay, this question has evolved a bit, and I want to try to start (over) with the basic goals I'm shooting for:
Create library code that wrappers legacy C-language entities in C++ resource acquisition is initialization and also provides basic or better exception guarantee.
Enable clients of this code to use it in a very natural C++ fashion w/o creating a lot of overhead to existing code to convert it to use the C++ wrapper objects (i.e. automatic conversion to appropriate legacy types, constructors that take legacy types, etc.)
Limit the namespace impact of the library code. Ideally, The library would have several sub-namespaces that provide related functionality that limit the volume and impact of using namespace X type declarations - much as the boost libraries do (i.e. use of details namespaces to only inject those symbols that the user would reasonably want to use, and hide those that are implementation details; also limit the extent of possible new meanings to existing symbols, to avoid surprising implicit conversions within user-code)
Require that clients explicitly ask for those parts of the library that they actually want to inject into their code base. This goes hand in hand with limiting the impact of inclusion of the the library's headers. The client code should have a reasonable level of control over which parts of the library are going to be automatically used for name-resolution when they compile their code.
My own library code should not have to be riddled with refactor-brittle code constructs. It would be ideal if the library's headers didn't have to constantly declare private typedefs in order to have access to the rest of that section of the library. Or in other words: I want my library to be able to be written as intuitively as my clients get to when making use of said library. Name resolution should include the namespace that the library is defined within in addition to any others that have been explicitly "using'd".
I come across this scenario often, and am looking for a better way...
I have a class, C in namespace N. C has a member, Free. It free's something that C manages, and allows C to manage a new thing.
There are several global Free functions. There are also a few helper functions in the same namespace N as C, one of which is a helper that free's the thing managed by C, named free.
So we have something like:
namespace N {
void free(THING * thing);
class C
{
public:
... details omitted...
free()
{
free(m_thing); // <- how best to refer to N::free(THING&)
}
}
} // namespace N
I could use N::free(m_thing). But that seems unfortunate to me. Is there no way to refer to that which is outside the class scope but without resolving absolute namespace (a relative one step out scope-wise)?
It seems to me that having to name N::free is obnoxious, since you wouldn't have to if this were a free-standing function. Nor would you need to if the class's method name happened to be different (e.g. dispose). But because I've used the same name, I cannot access it without having to specify what amounts to an absolute path - rather than a relative path - if you'll indulge me the analogy.
I hate absolute paths. They make moving things around in namespaces very brittle, so code-refactoring becomes much uglier. Plus, the rules of how to name things in function bodies becomes more complex with the current set of rules (as I understand them) - less regular - inducing a schism between what one expects and what one gets as a programmer.
Is there a better way to access free-standing functions in the same namespace as a class without having to absolutely name the free-function absolutely?
EDIT:
Perhaps I should have gone with a less abstract example:
namespace Toolbox {
namespace Windows {
// deallocates the given PIDL
void Free(ITEMIDLIST ** ppidl);
class Pidl
{
public:
// create empty
Pidl() : m_pidl(NULL) { }
// create a copy of a given PIDL
explicit Pidl(const ITEMIDLIST * pidl);
// create a PIDL from an IShellFolder
explicit Pidl(IShellFolder * folder);
...
// dispose of the underlying ITEMIDLIST* so we can be free to manage another...
void Free();
};
So ITEMIDLIST* come from a variety of places, and are destroyed with CoTaskMemFree(). I could introduce Pidl as a global name - as well as all of the helper functions in the "Windows Shell.h" header that is part of my toolbox library.
Ideally, I would segment some of the tools in my library by what they relate to - in this case the above all relates to COM programming in Windows. I have chose Toolbox as the base namespace for my libraries stuff, and was currently thinking I'd use Toolbox::Windows for very windows-y functions, classes, etc.
But the C++ namespace and name-resolution rules seem to make this very difficult (hence this question). It makes it very unnatural to create such segmentation of my code - since koenig lookup fails (since ITEMIDLIST is not in my Toolbox::Windows namespace), and I don't have the ability to move it there! Nor should I. The language should be flexible enough, IMO, to both allow for extension libraries such as my Toolbox library to extend other folks code without having to inject my extensions into their namespace (which, in the case of Win32 and the general vast majority of code that exists today, is the GLOBAL NS - which is the whole point of making namespaces in the first place: to avoid global NS crowding / pollution / ambiguity / programming surprises).
So, I come back around to, Is there a better way to do this: Extend existing libraries of code while not polluting their NS with my extensions but still allow for intuitive and useful name resolution as one would expect if my code were in their NS but explicitly introduced by the client of my code (i.e. I don't want to inject my code willy-nilly, but only upon explicit request)?
Another Thought: Perhaps what would satisfy my above criterea would be if I had the following:
using namespace X {
code here...
}
Where I could place such a construct anywhere, including in a header, and I would not have to be concerned about dragging X into my client's code, but I would have the same freedom to write my source code as I would if I were in the root namespace.
I don't see to avoid having to qualify namespace-scope free() here, but it should be noted that this is not the same as an "absolute path". For one thing, if you have nested namespaces, you only have to refer to the innermost one:
namespace N1 {
namespace N2 {
namespace N3 {
void free(THING * thing);
class C {
public:
free() {
N3::free(m_Thing); // no need to do N1::N2::
}
};
}
}
}
[EDIT] in response to edited question. Again, I do not see any way to do this in the exact scenario that you describe. However, it doesn't seem to be idiomatic C++ approach - the more common way to do the same is to provide your own wrapper class for ITEMIDLIST that manages all allocations, RAII-style, and exposes the original handle (e.g. via conversion operators a la ATL, or an explicit member function like c_str() if you want extra safety). That would remove the need for your free altogether, and for any other free function that you might want there, since you control the wrapper type and the namespace it's in, you can use ADL as usual.
[EDIT #2]. This part of the question:
allow for intuitive and useful name resolution as one would expect if my code were in their NS but explicitly introduced by the client of my code (i.e. I don't want to inject my code willy-nilly, but only upon explicit request)?
Isn't this precisely what you putting it in a namespace, and your client writing using namespace ..., will achieve?
You have two options:
Fully qualify function name.
Let Koenig lookup do the job (if THING belongs to namespace N).
I'd choose the first one with such popular function name as free.
Alternate option is to use m_thing->Release() or something like that.
Yuu could write ::free(m_thing);. This will call the global free() function. However, if you have another free() function outside the N namespace, you've got yourself into trouble. Either change names of some of your functions or use the function name with explicit namespace.
It seems to me that there is a problem of design here.
I find strange to have the same identifier used both as a free-function and a class method, it really is confusing. I try to minimize the occurence as much as possible, although I admit that it happens for swap...
I try not to qualify the names within the method, but here of course you run the risk of hiding, where MyClass::free hides the N::free method, which never participates in the lookup... tried to find about the scope resolution here but could not find the exact passage.
For swap I simply use:
class MyClass
{
void swap(MyClass& rhs)
{
using std::swap; // Because int, etc... are not in std
swap(m_foo, rhs.m_foo);
swap(m_bar, rhs.m_bar);
}
};
inline void swap(MyClass& lhs, MyClass& rhs) { lhs.swap(rhs); }
Therefore I make sure that the right method will be included in the lookup, and avoid falling back on a 'global' method if any.
I prefer this approach to explicit naming and usually bolts using and typedef declaration at the top of the method so that the actual code is not bloated.
I would use a completely different approach to what you are trying to accomplish. I think you need a bit of redesigning. Remove the globals and make a factory/abstract factory that will fabricate (create an instance of your class) and destroy it with the destructor. In fact, that would be the RAII idiom.