I have few classes with long names as well as their member functions. In C++ there is a trick which allows you to use one namespace and declare function:
namespace_name::foo();
and define it like this:
namespace namespace_name{
foo() {}
}
For clarity of the code I'm wondering if there is a similar way to substitute definitions of functions:
LongClassName::LongFunctionName() {}
I'm sorry if I used improper vocabulary, but had no idea how to describe the problem.
In C++ there is a trick which allows you to use one namespace and turn
This "trick" allows you to call function without specifying full function name with namespace. For function definition that does not work neither for namespace nor class. For namespace level function you either have to put that function definition inside namespace or mention it explicitly:
namespace foo {
void bar(); // foo::bar() declared
}
// you can define it as this
namespace foo {
void bar() {}
}
// or this
void foo::bar() {}
// this does not work
using namespace foo;
void bar() {} // ::bar() is defined here not foo::bar()
for class method definition - class name must be always used (and possibly namespace as well if any) unless you define them inside class itself (and declare them inline implicitly):
class VeryLongName {
public:
void method1() {}
void method2() {}
};
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 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).
What is the correct way to call one function from another from the same namespace when using the 'using namespace' keyword in the implementation? I get following error:
Call to 'bar' is ambiguous
when compiling this:
// Foo.h
namespace Foo
{
void bar();
void callBar();
}
// Foo.cpp
#include "Foo.h"
using namespace Foo;
void bar() {/* do something */}
void callBar() {bar();}
It appears that you are providing definitions of bar and callBar in the cpp file. In this case you should put the functions in the namespace Foo where they are declared, rather than importing that namespace with using:
#include "Foo.h"
namespace Foo {
void bar() {/* do something */}
void callBar() {bar();}
}
The using namespace directive tells the compiler that you want to call functions and refer to classes from the namespace Foo without qualifying their names explicitly; you can have multiple such directives in your file. It does not tell the compiler that the definitions that you provide below should belong to the namespace Foo, so the compiler dumps them in the top-level namespace.
The end result is that the compiler sees two bars - the Foo::bar() declared in the Foo namespace, with external definition, and ::bar() defined in your cpp file in the default namespace.
You have two bars here. one declared in namespace Foo but not defined and another declared and defined in the global namespace. Both are reachable from the call site because you are using using namespace Foo;, hence the ambiguity for the compiler.
If the definitions of the functions are for the ones in the Foo namespace then you should put them in there too.
namespace Foo {
void bar() {/* do something */}
void callBar() {bar();}
}
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;
}
Assume having a C++ class. And there's a namespace which should be visible only inside my class. What to do for that?
class SomeClass
{
using namespace SomeSpace;
public:
void Method1();
void Method2();
void Method3();
};
namespace SomeSpace
{
/*some code*/
};
using namespace X; is called a using directive and it can appear only in namespace and function scope, but not class scope. So what you're trying to do is not possible in C++. The best you could do is write the using directive in the scope of the namespace of that class, which may not be desirable.
On second thought, though, analyzing your words,
Assume having a C++ class. And there's a namespace which should be
visible only inside my class. What to do for that?
I'd suggest something like the following, which I am not sure is what you want.
class A
{
public:
void Method1();
void Method2();
void Method3();
private:
class B
{
//public static functions here, instead of namespace-scope
// freestanding functions.
//these functions will be accessible from class A(and its friends, if any)
//because B is private to A
};
};
No but you can do it like that:
namespace SomeSpace
{
/*some code*/
};
using namespace SomeSpace;
class SomeClass
{
public:
void Method1();
void Method2();
void Method3();
};
Though it is not recommended either to apply the using namespace directive in header files and often considered as a bad style. It is OK to put in in a source file (.cpp) of your class.