How can I create bunch of methods that doesn't depend on any object ( in my file there is no classes , no objects , no main , nothing but the methods) all in one cpp/hpp file and how to declare them ?
Create a namespace. Something like this:
Utils.h
namespace Utils
{
void myMethod();
}
Utils.cpp
namespace Utils
{
void myMethod()
{
//Implementation
}
}
If you want them to be public, i.e. available in multiple translation units, the best way is to include them in a namespace, declare them in the header and implement them in a single implementation file:
//functions.h
namespace MyFunctions
{
void foo();
void goo();
}
//functions.cpp
namespace MyFunctions
{
void foo() {}
void goo() {}
}
IMPORTANT
If you provide the definition in the header, you should mark them inline, otherwise including that header in multiple translation units might result in a linker error:
//functions.h
inline void foo() {
//..
}
inline void goo() {
//..
}
If you only want them available in a translation unit, define them in that implementation file in an anonymous namespace (or declare them static):
//fileThatUsesFunctions.cpp
namespace
{
void foo() {}
void goo() {}
}
You declare them the same way you would in C. It can be within a namespace or outside of a namespace. There is no difference other than the fact that they are not in a class.
If you want to use the functions in C later you should prepend them with extern "C".
extern "C" void foo();
Nothing stops you from writing free functions. If you think that a function should be global then free functions are quite appropriate.
You should place them in a namespace. Naveen's example is spot on.
As an additional note, if you wish to hide certain functions or data units within the namespace (thereby mimicking 'private' access), place those functions and data units in an anonymous namespace, nested within the parent namespace. For example:
namespace Foo
{
publicFunction1();
publicFunction2();
namespace
{
privateFunction1();
std::vector<Bar> privateData;
}
}
Items within a nested, anonymous namespace are only accessible to the items within the parent namespace. I've found this to be singularly useful.
To define a function that doesn't depend on an object simply declare them directly.
// MyFile.h
int some_function();
// MyFile.cpp
int some_function() {
return 42;
}
Using C++ though it would be a good idea to declare them in a namespace though. This doesn't give them a dependcy on an object but does reduce global namespace pollution
// MyFile.h
namespace MyNamespace {
int some_function();
}
// MyFile.cpp
using MyNamespace;
int some_function() {
return 42;
}
Related
Suppose I have a class Foo like this:
foo.h:
namespace mine {
class Foo {
Widget widget_;
public:
void bar();
// some other members...
};
} // namespace mine
foo.cpp:
#include "foo.h"
namespace mine {
void Foo::bar() {
// Some very long code
}
} // namespace mine
where I want to split bar() into multiple functions for readability reasons. The functions themselves don't have any particular meaning to Foo (or any other entity than Foo::bar()) and are only used to split up bar(), so according to this discussion I would do the following in the source file:
foo.cpp (refactored):
#include "foo.h"
// anonymous namespace to put all helper functions
namespace {
void computeResult() { ... }
void modifyWidget(Widget& w) { ... }
void doThis() { ... }
void doThat(Widget& w) {
// ...
modifyWidget(w);
}
} // <anonymous> namespace
// actual methods are defined here
namespace mine {
void Foo::bar() {
::doThis();
::doThat(widget_);
::computeResult();
}
} // namespace mine
So I am defining an anonymous namespace in the source file in order to define the helper functions, such that I have static linkage and the helper functions are not visible from outside the source file. One thing that looks odd to me is that class methods depend on functions that are not part of the class, but then we would not be able to use even the standard library if this was an issue.
Is this approach sensible? Do you have better suggestions?
Is there a problem with passing the private member Foo::widget_ to some freestanding function that modifies it (doThat())? I'm assuming here that in the narrow context of a static linkage helper function, the callers/callees know what they are doing.
Yes, it's sensible. It's also not uncommon, and it's my impression that it's gaining popularity.
Linkage has no effect whatsoever on how functions work, and a private member variable works exactly like all other variables (except you can't access its name from the outside).
That is, it's exactly like passing any variable to any function.
I'm doing online programming tests like leetcode, which requires only one .cpp file, so I have to place everything into one .cpp file.
And I used to write main() function ahead of any other functions, but that way I have to forward declare every function I use, which is very annoying. So I think of something like the snippet below:
namespace function;//oop,there is no such forward declaration
int main()
{
using namespace function;//compiler could not find this actually;
f1();
...
}
namespace function
{
f1(){...};
f2(){...};
...
}
But the compiler complains, since there is no forward declaration of namespaces (unlike functions), which makes the namespace invisible to the compiler.
Is there any way to forward declare a namespace? Just like
void f1();
int main()
{
f1();//ok,because there is a forward declaration
}
void f1()
{ ...}
The nearest thing to forward-declaring a namespace is to rely on the fact that they can be split up (unlike a class declaration), even into different translation units! Hence you can write
namespace funcion // [sic]
{
}
before main. Note well the braces.
If not having to forward declare functions is the most important goal, you can abuse the fact that a class also defines a namespace scope where you don't have to forward declare member functions.
Something like this:
struct program
{
int main()
{
f1();
f2();
return 0;
}
void f1(){}
void f2(){}
};
// The real main still needed here
int main()
{ return program{}.main(); }
Technically this works, but still not really recommended.
This won't solve your problem.
You can declare the namespace earlier like this:
namespace function {};
int main()
{
using namespace function;
f1();
}
namespace function
{
void f1() {}
}
but f1 is still not declared in main.
How about extracting the function declarations to a header file and including it?
somefile.h
#pragma once
namespace function {
void f1();
};
somefile.cpp
#include "somefile.h"
int main()
{
using namespace function;//compiler could not find this actually;
f1();
}
namespace function
{
void f1() {}
}
so I have to place everything into one .cpp file
Then just forget the #include and do one of the following:
a. put the declaration namespace function { void f1(); } above int main() and the definition (function body) below int main()
b. put the int main() last, so that you don't require additional declarations
I've got some embedded C++ code that's currently written in a very C-like way, and I'd like to convert it to use namespaces for better code organization. Currently I hide my private file scope functions and variables in anonymous namespaces, but I'm not sure where to hide it using this new pattern. Should I still use an anonymous namespace, or is adding it to the namespace in the .cpp file, but not the header file sufficient enough to prevent external access?
More specifically, I've got code that looks like this:
UI.h
#ifndef UI_H
#define UI_H
//Public data declarations
extern int g_UiPublicVar;
//Public function declarations
void UI_PublicFunc();
#endif
UI.cpp
#include "UI.h"
//Private data and functions
namespace
{
int m_PrivateVar = 10;
void privateFunc()
{
//Do stuff!
}
}
//Public data definitions
int g_UiPublicVar = 10;
//Public function definitions
void UI_PublicFunc()
{
m_PrivateVar++;
privateFunc();
}
...and I'd like to restructure it to look like this:
New UI.h
#ifndef UI_H
#define UI_H
namespace UI
{
//Public data declarations
extern int publicVar;
//Public function declarations
void publicFunc();
}
#endif
New UI.cpp
#include "UI.h"
namespace UI
{
//Public data definitions
int publicVar = 10;
//Public function definitions
void publicFunc()
{
m_PrivateVar++;
privateFunc();
}
}
...where should I put m_PrivateVar and privateFunc()?
The solution is to put it in an anonymous nested namespace for the private elements:
File UI.cpp:
namespace UI
{
namespace // nested private namespace
{
int m_PrivateVar = 10;
void privateFunc()
{
//Do stuff!
}
}
//Public definitions
...
}
The other compilation units then can't see it, as the anonymous namespace is unique for each compilation unit.
You can test this setting using a third compilation unit, including UI.h and trying to create access to the private function:
File main.cpp:
#include "UI.h"
namespace UI {
extern void privateFunc(); // Hijack temptative
}
int main(int ac, char**av)
{
UI::publicFunc(); // yes !!
UI::privateFunc(); // compiles, but generates a linking error
// private remains private :-) !!!
}
Even if the hijack temptative would also use an anonymous namespace, it wouldn't work and still result in linking errors, because, as already said, the anonymous namespace is unique for each compilation unit.
I am trying to define a common interface to a set of functions and classes that will have multiple different backend implementations (Using different libraries).
As such I'd really rather, simply, define a function in one place and not in each separate namespace.
For example, I have a global function:
extern void Func();
Now I want to have 3 separate implementations of that function. One would be a straight C, One would be a hand coded assembler and one would be using library 'x'.
I am effectively trying to avoid doing the following:
namespace C
{
extern void Func();
}
namespace Asm
{
extern void Func();
}
namespace LibX
{
extern void Func();
}
Is there a good pattern to avoid doing this? When there are 100 odd functions it will become much more of a pain.
The only idea I can think of is to move all the definitions into a header file that has no header guards and then doing:
namespace C
{
#include "Functions.h"
}
namespace Asm
{
#include "Functions.h"
}
namespace LibX
{
#include "Functions.h"
}
Is there a better way of doing this that anyone can think of?
Make it a virtual function in an abstract base class. Implement it whenever you feel like it in a derived class.
class Foo{
public:
virtual void bar() const=0;
}
class FooASM:public Foo{
public:
virtual void bar() const{ ... }
}
etc.
I guess you want static polymorphism - means a template or a macro:
Template:
#include "C_Functions.h"
#include "Asm_Functions.h"
#include "LibX_Functions.h"
enum Namespace
{
NamespaceC,
NamespaceAsm,
NamespaceLibX
}
template <Namespace> Func();
template <> inline Func<NamespaceC>() { return C_Func(); }
template <> inline Func<NamespaceAsm>() { return Asm_Func(); }
template <> inline Func<NamespaceLibX>() { return LibX_Func(); }
const Namespace NSpace = ...
inline void f() {
Func<NSpace>()
}
An advantage is: You may have a common implementation for a specific function.
Similar you may do with macros (or you combine it)
I fear it ends up in #ifdef ... anyway, unless you try to have one lib for any hardware/system (which is pointless, in my view).
I have some inline functions contained within a namespace in a header file and am not currently in a position to move them into a cpp file. Some of these inline functions use magic constants, for example:
// Foo.h
namespace Foo
{
const int BAR = 1234;
inline void someFunc()
{
// Do something with BAR
}
}
However, I want to make these magic constants private - any ideas how? My first thought was to use an anonymous namespace thus:
// Foo.h
namespace Foo
{
namespace
{
// 'private' constants here
const int BAR = 1234;
}
inline void someFunc()
{
// Do something with BAR
}
}
However, this doesn't work and Foo::BAR is available to any cpp file that includes Foo.h? Is there a way to do this without creating an implementation cpp file?
You can't, anonymous namespaces work for the translation unit they are defined in (or included into in your case).
You could consider moving them into a detail namespace to signal to the user that they are internal details:
namespace foo {
namespace detail {
int magic = 42;
}
// ... use detail::magic
}
How about:
namespace Foo {
class foo_detail {
private:
enum {
BAR = 1234,
};
friend void someFunc();
};
inline
void someFunc() {
// something with foo_detail::BAR
}
}
This makes the constant nonaccessible for anyone else than the functions you mark as friends. You can make the class nonconstructable by making the constructor private to make sure that noone does try to instanciate the class.
Put them in a special namespace or name them specially, combined with a project convention that such things are non-public:
namespace foo {
namespace detail { // as in "implementation details"
inline int answer() { return 42; }
const int perfect = 28;
}
std::string _question(); // not part of foo's "public interface" by convention
int this_is_public() {
using namespace detail; // now don't have to prefix detail::
return answer() + perfect + _question().length();
}
}
Anyone using names documented as non-public will circumvent any "protection" you try; which highlights the real concern: documenting what's part of the public interface and may be relied upon.
Unnamed namespaces solve a different problem: getting names unique to a particular TU. They won't help here.