Calling an "external" function from a class method - c++

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.

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.

Where to place STL / template code c++?

Hi I have what is hopefully a quick question. As part of homework I've been asked to write my own template vector class (most of the code is there it just needs to be expanded upon). While I understand HOW it works and WHAT it does I have no idea WHERE to put the code or reference it as I have never seen it in context within a program.
Do I create a new cpp file with all this information in it, or do I just add it in above my main method? If I create a new file (either cpp or h) how do I reference it, with just a #include like normal?
This might seem fairly simple but I've tried creating a new .h file and then including it in my main program but I always get scope definition errors.
Most compilers require you to put all the template code in a header file, rather than a source. This is due to the way template expansion works. You just include that header in whichever files need to use your vector class.
Some things to watch out for when creating a header:
Prevent multiple inclusion. If your compiler supports #pragma once you can put that at the top, otherwise use the #ifndef MY_HEADER_H ....... pattern.
Don't forget to put a semi-colon on the end of your class!!!!
Never put using namespace whatever; in the outer scope of a header (it's okay to use it within block scope such as namespace something { ... } or a function).
Be careful of name conflicts with std::vector if you are calling your class vector - make sure nobody has imported the std namespace prior to including your header.
One point you need to keep in mind is that you should place template declaration and definition together in the header file because of the compilation model of templates.
You can create a header file for the templated vector class and include this header file when you would like to use it in other .h or .cpp files.
You can also put them together inside main, but the previous option is better for you to maintain your code.

What is the difference between using and include in c++?

I know that include is for classes and using is for some built-in stuff, like namespace std... When you include something, you can create objects and play around with them, but when you are "using" something, then you can use some sort of built-in functions. But then how am I supposed to create my own "library" which I could "use"?
Simply put #include tells the pre-compiler to simply copy and paste contents of the header file being included to the current translation unit. It is evaluated by the pre-compiler.
While using directive directs the compiler to bring the symbol names from another scope in to current scope. This is essentially put in effect by the compiler.
But then how am I supposed to create my own "library" which I could "use"?
Namespaces are something which are used for preventing symbol name clashes. And usually every library implementer will have their functionality wrapped up in one or many namespaces.
'include' basically does a copy-paste the value of a file to the location of the "include" line. This is used to make your source code (usually .c file) aware of a declaration of other source code (usually sits in .h file).
'using' basically tells the compiler that in the next code you are using something (usually a namespace) so you won't have to do it explicitly each time:
Instead of:
std::string a;
std::string b;
std::string c;
You could write:
using namespace std;
string a;
string b;
string c;
You can say both gives the same functionality but #include is not done by compiler where as using is done by compiler. In #include all the code is placed in file where #include is given where as namespace gives the definition of function and variables from one scope to another. If you have function with same name in two header files and both are included then there will be an error of redeclaration but you can use same name functions if they are from different namespaces.

How can I `unuse` a class?

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.

Declaring using statement after namespace declaration

I am writing a utility library which is made up of several "Packages". The classes in each package are contained in various namespaces. I have an idea as to how I can simplify the situation by automatically declaring using statements at the end of class declarations (see below), this will avoid having the programmer do it in a cpp file.
namespace Utility
{
class String
{
// Class Implementation
};
}
using Utility::String;
My understanding is that if the user includes the header String.h and String is in Utility then the programmer will want to use String. Obviously this could be bad if there are outside classes chain including a bunch of files which dirty up the namespace so I thought how about making it a #define instead.
namespace Utility
{
class String
{
// Class Implementation
};
}
#ifdef AUTO_DECLARE_NAMESPACE
using Utility::String;
#endif
That way, programmers that want this extended functionality can get it.
Would this a good idea or is there something I'm overlooking?
There is no point in using namespaces if you are just going to add a using declaration for each and every name declared in the namespace.
Let users of your header files decide how they want to use the headers. If someone wants to use a using declaration, let him do it in the .cpp file directly; this will make the code in that .cpp file clearer since it will be apparent where the name originated.
This seems at best pointless, and at worst annoying.
What is wrong with having developers decide which namespaces to use and what to qualify fully?
Honestly, I believe that's what the using namespace directive is for. There's no need for you to add this preprocessor mechanism, considering the using namespace directive does just that.
Couldn't you have another .h file with all your usings like my_lib_import_names.h and just #include that to get what you want?
You would probably have problem with classes not being declared but you could probably bypass it by using something like:
#ifdef UTILITY_STRING_H_
using Utility::String;
#endif
..
#ifdef UTILITY_SOMETHING_ELSE_H
using Utility::SomethingElse;
#endif
..
What do you think?
That way you could retain the "expected" behavior in your library .h but also have your the way you like. You also get to keep the benefit of the namespace over your classes (at the expense of having to maintain your new .h file).