Disambiguate the term "Helper function". One definition is a convenience
function that you use all the time just to get some job done. Those
can live in the main namespace and have their own headers, etc.
The other helper function definition is a utility function for a single class or class family.
// a general helper
template <class T>
bool isPrinter(T& p){
return (dynamic_cast<Printer>(p))? true: false;
}
// specific helper for printers
namespace printer_utils {
namespace HP {
print_alignment_page() { printAlignPage();}
}
namespace Xerox {
print_alignment_page() { Alignment_Page_Print();}
}
namespace Canon {
print_alignment_page() { AlignPage();}
}
namespace Kyocera {
print_alignment_page() { Align(137,4);}
}
namespace Panasonic {
print_alignment_page() { exec(0xFF03); }
}
} //namespace
Now isPrinter
is available to any code including its header,
but print_alignment_page
requires a
using namespace printer_utils::Xerox;
directive.
One may also reference it as
Canon::print_alignment_page();
to be more clear.
The C++ STL has the std::
namespace which covers almost all of its
classes and functions, but it breaks them up categorically into over 17 different headers to allow the coder to get the class names, function names, etc out of the way if they want to write their own.
In fact, it is NOT recommended to use using namespace std;
in a header file or, as is often done, as the first line inside main()
. std::
is 5 letters and often seems a chore to preface the function one wants to use (especially std::cout
and std::endl
!) but it does serve a purpose.
The new C++11 has some sub-namespaces in it for special services such as
std::placeholders,
std::string_literals,
std::chrono,
std::this_thread,
std::regex_constants
that can be brought in for use.
A useful technique is namespace composition. One defines a custom namespace to hold the namespaces you need for your particular .cpp
file and use that instead of a bunch of using
statements for each thing in a namespace you might need.
#include <iostream>
#include <string>
#include <vector>
namespace Needed {
using std::vector;
using std::string;
using std::cout;
using std::endl;
}
int main(int argc, char* argv[])
{
/* using namespace std; */
// would avoid all these individual using clauses,
// but this way only these are included in the global
// namespace.
using namespace Needed; // pulls in the composition
vector<string> str_vec;
string s("Now I have the namespace(s) I need,");
string t("But not the ones I don't.");
str_vec.push_back(s);
str_vec.push_back(t);
cout << s << "\n" << t << endl;
// ...
This technique limits exposure to the whole std:: namespace
(it's big!) and allows one to write cleaner code for the most common code lines that people write the most often.
static
keyword?