How can I `unuse` a class? - c++

In our huge codebase, in one of the include files, we have the statement
using std::some_function
However, I want to "unuse" some_function and use another some_function. I cannot modify this header because most of the code base depends on it.
Is there a possibility to do so?

I don't think there is. You should place your function in a namespace and qualify its use:
namespace MyNamespace
{
void some_function();
}
//...
MyNamespace::some_function();
Of course, the best you can do is remove the using directive and fix the code - but I (sadly) do understand why this isn't always an option.
EDIT: Just maybe, the using directive isn't there because of lazyness, but someone actually wants you to think twice before implementing your own some_function.

Depends what you want the scope of the "unuse" to be.
If it's scoped (to your own namespace or even better to a function) then you can put using MyNamespace::some_function; in your scope.
If it's global scope then the author of the original header has overruled you - in effect they got to the name ::some_function first, and they've prevented you from usingit for anything else. They shouldn't have pulled a std function into the global namespace, but you just have to live with their error.
Assuming that you don't want to make the same mistake they made, you only want the "unuse" to apply to one source file, you're not putting it in global scope in a header yourself. In that case you could #define some_function MyNamespace::some_function, but I don't recommend it because readers/maintainers of the code won't expect to have to realise that a lower-case name is actually a macro.
If some_function is a function (not a class as in the title), and you're only dealing with one overload (for example void some_function(), then there's another ugly workaround. Add another parameter:
static void some_function(int) { MyNamespace::some_function(); }
Then you can call it as some_function(0) and get the MyNamespace version. But if you're going to type extra text (in this case 0) I should think you might as well do it the expected way: make that extra text be MyNamespace::, or just use a different name.

Related

Namespace questions: forward declaration and mixing namespaces

I'm not very familiar with C++, and this is my first time working with more than just the namespace std. What is the difference between the following?
using MyNameSpace::MyClass;
vs
namespace MyNameSpace {class MyClass;}
After both, it seems I can now create a MyClass object. Is one way better than the other? Also, if I don't do either, can I still reference MyClass by appending MyNameSpace::MyClass before it every time I need to?
Next, if I forward declare using the second option, do I still need to #include "MyClass.h"? In my (not very good) understanding, in C++, you make header files in order to forward declare classes so that they can be used later. So if you have already forward declared, would you still need to include the header file?
Finally, when working with multiple namespaces (namespace Architecture and namespace Router), I have an error I don't know how to explain. In one of my header files, I have using std::vector as the first line after my #include statements. This statement is not within any namespace, I think. When compiling, I receive the error, "'Architecture::std::vector' has not been declared". To remedy this, I can change the statement to using ::std::vector to tell it to look at global scope for std::vector.
However, I don't understand why this problem exists. Since I am declaring using std::vector at the top of my header file, why am I not already at global scope? A better question might be: how can I tell which scope I am in at the top of a header file? Additionally, I thought in C++ (and according to this answer What is the difference between writing "::namespace::identifier" and "namespace::identifier"?), if you couldn't find the name within the current scope, you would automatically look up a level until you reach global scope.
I hope these questions are well written and understandable. Hopefully I can get some answers to these questions and begin to understand how namespaces interact with one another.
using MyNameSpace::MyClass;
This using-declaration injects the name MyClass into the current scope, referring to the entity denoted by MyNameSpace::MyClass, which must have been previously declared.
namespace MyNameSpace {class MyClass;}
This is a forward declaration of the class MyClass in the namespace MyNamespace.
After both, it seems I can now create a MyClass object.
Unlikely in the second case, unless you have a using namespace MyNamespace; and the full definition of MyClass is available.
Is one way better than the other?
They do completely different things.
Also, if I don't do either, can I still reference MyClass by appending MyNameSpace::MyClass before it every time I need to?
If using MyNameSpace::MyClass; compiles (i.e., MyNameSpace::MyClass has been declared), then you can do this. Otherwise, you can't.
Next, if I forward declare using the second option, do I still need to
#include "MyClass.h"? In my (not very good) understanding, in C++,
you make header files in order to forward declare classes so that they
can be used later. So if you have already forward declared, would you
still need to include the header file?
Headers usually carry the full class definition - which includes declarations of all its data members and member functions. A forward declaration like class MyClass; will not allow you to create a MyClass object, since the compiler would not know how much memory to allocate for that object or what constructors are available.
However, I don't understand why this problem exists. Since I am
declaring using std::vector at the top of my header file, why am I not
already at global scope? A better question might be: how can I tell
which scope I am in at the top of a header file? Additionally, I
thought in C++ (and according to this answer What is the difference
between writing "::namespace::identifier" and
"namespace::identifier"?, if you couldn't find the name within the
current scope, you would automatically look up a level until you reach
global scope.
This sounds like a problem of missing braces. If a header you wrote did not close namespace Architecture, then anything you include after that header will be put into the Architecture namespace by accident. If that's not the problem, please post a MCVE.

When to use "::" for global scope in C++?

Every once in a while, I stumble across some code that I'm maintaining that challenges the way I think about my code style. Today was one of those days...
I'm aware that about why you would want to use the scope operator to define global scope. In fact, here scope resolution operator without a scope is a great link tell you why.
However, I saw something that made me think today. All the classes in question were wrapped into a namespace for the project (good!), but I did see copious usage of the global scope operator. Namely, it was used for everything from C libraries (with the exception of uint8_t and the like... yes, the programmer used the .h version of this library since apparently the version of g++ they were running still threw warnings about the new C++ standard). Is this useful? I view this as just as a waste of characters (reminds me of using the this pointer... except in the case of the copy constructor and assignment operator where it helps in clarifying which object is which). Am I missing something? Sure, someone can come around and name something along the lines of usleep() or stderr (where I saw the most usage of "::"), but won't they know that doing so will probably break something horribly? At what point do you say "screw it" in terms of the scope operator and just tell yourself that someone who names a function a certain way within your namespace is asking for trouble?
So my question is... what is the "correct" (subjective I understand) way of using the global scope operator in this context? Should everything not included in std or your own namespaces have the global scope explicitly defined? I tend to err on the side of caution and use "std::" to avoid the using directive, but is anything gained from using the global scope operator here? I tend to think for clarity's sake it does lend to the fact that we aren't getting the variable or function in question from the current namespace, but I'm torn between including it and not given today's developments.
As always, thanks for the help and guidance as I look to make my code cleaner, more readable, and (of course) significantly more awesome.
I use it quite infrequently; only when some ambiguity needs resolving for whatever reason. This is pretty subjective, though.
There may be some occasions (say, inside a template) where you're worried about ADL causing ambiguities only in certain cases:
template <typename T>
void foo(T t)
{
::bar(t); // :: just in case there's a `bar` in `T`'s namespace
}
There is almost no correct answer to this as it's almost totally style related, with the exception that if you think you may want to change from where you are going to import some declaration(s)/definition(s), in which case, when you use them, you don't specify any scope and import them using the using directive (to import a subset from the namespace) or the using namespace directive to import the entire set from the namespace.
Mostly the using directive is used as a convenience directive, but it is a powerful way to direct which declarations/definitions are used. My preference is to not specify the scope and import the declarations. Doing this allows for easy changes if ever they are needed while reducing visual noise. Also, specifying the scope would mean I'd be "locked in" from where I am getting the declarations (well, I'd have to do a global search and replace to change it).
If ever there is a conflict (you try an use a declared item with the same name that has been imported from more than one namespace) the compiler will let you know, so there's no real danger.
Readable code is that has the least amount of noise. namespace prefixes normally provide nothing but noise. So baseline is to not have them at all.
Namespaces were introduced to C++ mainly to handle 3rd party stuff out of one's control. To allow libraries drop prefixing, while clients can use terse names by applying using.
Just because you can have the same name in many namespaces does not imply it is a good idea to too. If a project uses some environment, platform API, library set, whatever that puts name in global, those names are better be avoided for other purposes. As with or without prefixes they will bear mental overhead.
Use of :: is rare in well-shaped code, and frequent uses appear in wrapper classes for that same functionality.
Consider the following cases.
Public library.
You are writing an exportable library with public headers. And you absolutely have no clue in what environment your headers will be included. For example, someone may do:
namespace std = my_space::std;
#include "your_header"
And all your definitions will be corrupted, if you simply use: std::list<int>, etc. So, it's a good practice to prepend :: to everything global. This way you can be absolutely sure what you're using. Of course, you can do using (in C++11) or typedef - but it's a wrong way to go in headers.
Collaborative .cc/.cpp files.
Inside your own code that is not exposed to public in any way, but still editable not only by you - it's a good practice to announce, what you're going to use from outside of your namespace. Say, your project allows to use a number of vectors - not only an std::vector. Then, where it's appropriate, you put a using directive:
// some includes
using vector = ::std::vector<int>; // C++11
typedef ::std::vector<int> vector; // C++03
namespace my_namespace {
...
} // namespace my_namespace
It may be put after all includes, or inside specific functions. It's not only gives control over the code, but also makes it readable and shortens expressions.
Another common case - is a mixing of global C functions and a C++ code. It's not a good idea to do any typedefs with function names. In this situation you should prepend C functions with the global scope resolution operator :: - to avoid compilation problems, when someone implements a function with a same signature in the same namespace.
Don't use :: for relative types and namespaces - or you'll lose the benefit of using namespaces at all.
Your own code.
Do what you want and how you want. There is only one good way - the way you fill comfortable with your own code. Really, don't bother about global scope resolution in this situation, if it's not requiered to resolve an ambiguity.

Calling an "external" function from a class method

I have a function that I want to call from within a class method. The function is in a file called mergeSort.cpp. Here is a snippet of the .cpp file that the class is implemented in:
// other includes
#include "mergeSort.cpp"
// other methods
void Servers::sortSites() {
mergeSort(server_sites.begin(), server_sites.end(), siteCompare);
}
// remaining methods
When I try to compile I get errors saying that mergeSort can't be found. I think this is because it's trying to call Servers::mergeSort. How would I go about calling an external function?
You have to use the "::" external namespace resolutor:
::mergeSort(...);
This tells the compiler to look for the function in the outer namespace. If this particular function is defined in another namespace or class, you have to specify it explicitly:
Namespace::mergeSort(...);
If you don't want to have to resolve the name completely each time you use it, you can import the name into the current namespace by either using:
using namespace Namespace;
or
using Namespace::mergeSort;
(where Namespace is the name in which mergeShort() is defined).
There seem to be a couple of issues here. Firstly, does Servers::mergeSort actually exist? You've speculated that it's looking for that, but you haven't actually said that there is such a thing. If there isn't, that's not the problem. In that case, a likely reason it can't see mergeSort would be that it's not in the global namespace (as other answers have speculated). If Servers::mergeSort does exist, then see Diego's answer.
A separate issue is -- are you including the .cpp file (which is generally a bit odd) because mergeSort is a template? If no, you should probably be including the accompanying .h I guess. If yes, a more usual pattern is to include the file with the template code in the header, like so:
// mergeSort.h
// <Begin include guard
// <Lots of header stuff>
#include "mergeSort.tpp"
// <End include guard>
Then you include mergeSort.h elsewhere, and it's one thing less for clients to remember.
Check if mergeSort() is in a particular namespace.

Shorter Calls/Names Without Using Defines

Simple question, how do I shorten a call/name without using defines.
For example, I have a singleton that I have to call that is within a namespace (I cannot use using namespace blabla because it is not allowed) like so:
MyFW::GameRoot::Instance()->DoSomething();
Now I can assign that to a variable, which works somewhat if I am using it multiple times within the same class/function, but using it in many classes/functions it becomes cumbersome. I decided to use #define for it:
#define MyFW::GameRoot::Instance() ROOT //defined in GameRoot.h
ROOT->DoSomething(); //Used where-ever GameRoot.h is included
Much better, and I really like it especially because now wherever I see ROOT (color coded through V-Assist) I know what it is immediately... unless I have a breakpoint there and I need Visual Studio to resolve ROOT to show up in the watch window (or even hover over it to quickly pull up the object in debug), which it cannot do.
Is there any other option? What do you guys do to shorten names? Simply use local/member pointers to store the instance?
Thanks!
You can't use using namespace ..., but can you use
namespace root=MyFW::GameRoot;
Then you can type
root::Instance()->DoSomething();
Defining a namespace like that is better than a #define. (I.e it can't get munged up somewhere else by mistake. The compiler knows what you are trying to do.)
Use local references:
MyFW::GameRoot& ROOT = *MyFW::GameRoot::Instance();
Do not use defines.
If you want to ease access across multiple functions, just use a helper function:
namespace {
MyFW::GameRoot* root() { return MyFW::GameRoot::Instance(); }
}
// ...
root()->DoSomething();
Two characters more, but it with comes type-safety included.
The good way to do this (but never in a header) is
using MyFW::GameRoot;
GameRoot::Instance()->DoSomething;
This is a using declaration and is different from a using directive, which is what you mentioned above.

Do you declare your module specific functions as static?

I am thinking it is a best practice to declare them as static, as it makes them invisible outside of the module.
What are your thoughts on this?
For C++, a better than static is to put it in an unnamed (anonymous) namespace. This is the preferred way to prevent pollution of the Global namespace.
namespace {
void myLocalFunction() {
// stuff
}
}
If it is truly an function which is internal only to that .c file, then yes. It should help avoid polluting the global namespace. Also, I think that the compiler is able to do some optimizations with calling conventions if the function is static since it knowns no other source file needs to know how to call it. This only really applies to c because as others have noted, c++ has namespaces to address this issue.
There was a lot about implementation details and not too much about concept.
Limiting the scope of variable/function etc.. is a good practice indeed. This is a basic concept of object oriented design - you want keep private as private. This way your interface is cleaner and code maintenance is easier. And you will not find one day that changing something that you considered as private broke compilation because somebody in another part of project liked your function and decided to use it.
In C, I make everything - functions and variables - static at file scope until I can demonstrate they're necessary outside the file. I'll make things static within a function if only that function will use them and they are not too huge. Basically, if the declaration is bigger than the rest of the function, I may put the declaration outside the function. And, of course, there's a header for the public services provided by a source file.
Agreed. As a consequence, the prototypes for the static functions must go at the top of the .c file, not in the .h file.
In C++, you should use an anonymous namespace, like so:
// foo.cpp
namespace
{
class Core { ... };
void InternalFandango(Core *);
}
void SomeGloballyVisibleFunction()
{
InternalFandango(&core);
}
Advantage: this is applicable to struct / class declarations, too.
In C, just mark the functions "static". There's nothing against using "static" in C++, too, but I've learnt to prefer the namespace, as it is one single concept that works for all declarations.
I think C and C++ have different constraints concerning static: in C you don't have namespaces and .c files are your modules, so it is really really important to put all non-public functions as static to prevent errors!
About the only potentially useful property I can think of for this use of "static" in C++, that anonymous namespaces don't provide, is that there's a warning in GCC you can switch on for unused static functions (a form of dead code). You don't get that for unused functions in anonymous namespaces, so in the unlikely event that you want the compiler to tell you when you stop using the function, do it that way.
In C code, make your functions static by default. Only make non-static functions and .h declarations for functions that will be needed by other modules.
In C++ code, put those functions that are local to the file into an anonymous namespace and make them static. In the GNU compiler at least, this will result in the best and smallest code, because no function will be written if all uses are inlined. If you intend it to be inlined, then of course marking it inline is even better than static.
I do not know why g++ writes the uncalled function bodies that are in anonymous namespaces into the output at all, but it does. Functions with hidden visibility seem to show up as well; marked as hidden symbols, but still producing unused code blocks in the object file. GCC probably doesn't understand that the code isn't needed in those cases. Or I am missing something, always possible.
If you're using GCC, then you should take a look at the visibility flag (see http://gcc.gnu.org/wiki/Visibility for a full discussion).
It'll hide symbols completely as opposed to marking them unreachable. That reduces the symbol table, and helps decrease link times.
Not only that, it opens the door for more inlining, if that's what you're after.
If by 'module' you just mean a CPP file, you could just place the declaration and the definition right in the CPP file.
In C++, you'd declare the function private like this:
class MyClass
{
public:
void publiclyAccessibleFunction();
private:
void onlyAccesibleFromWithinTheClass();
int some_member_parameter;
};
Note the onlyAccesibleFromWithinTheClass() function.