C++ function call within same namespace - c++

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();}
}

Related

Where to put helper functions pertaining to class method in C++

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.

Define members of a class using class's namespace in c++

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() {}
};

Keyword using namespace in C++

is there a logical reason that after the keyword using namespace, we can't have a function called for example myfunction in the namespace and another function called myfunction outside the namespace (with same prototype), but we can have it for variables ( myvariable in the namespace and myvariable outside it) ?
Of course you can have a function with the same name and signature in different namespaces -- that's part of the reason namespaces exist. The only consideration is that if you want to call it you will have to qualify its name.
namespace Foo {
void func();
}
namespace Bar {
void func();
}
using namespace Foo;
using namespace Bar;
func(); // does not compile -- which func()?
Foo::func(); // ok
Bar::func(); // ok

Calling a C++ namespace-qualified function within a template function in another namespace

If I have a default function 'foo' defined in a namespace in one header file:
//DefaultFoo.h
namespace DefaultFooNamespace
{
template <typename T>
void foo(T& x){/*...*/}
}
and overloads of foo defined in another namespace in one or more other header files, e.g., FooOverloads.h:
//FooOverloads.h
namespace FooOverloadsNamespace
{
template <typename T>
void foo(std::vector<T>& x){/*...*/}
void foo(std::string& x){/*...*/}
//etc.
}
and I have another function 'bar' which calls foo after bringing both DefaultFooNamespace and FooOverloadsNamespace namespaces into scope (note that I #include only DefaultFoo.h in Bar.h, as DefaultFoo.h contains a single function in a namespace which is intended never to be extended, unlike FooOverloadsNamespace which will be extended by the addition of additional overloads):
//Bar.h
#include "DefaultFoo.h"
namespace BarNamespace
{
template <typename T>
void bar(T& x)
{
//... do stuff then call foo
using DefaultFooNamespace::foo;
using FooOverloadsNamespace::foo;
foo(x);
}
}
'bar' won't compile unless I either make sure FooOverloads.h is #include'd before a #include of Bar.h, or I make sure that FooOverloads.h is #include'd in Bar.h, or alternatively I provide a declaration of a 'foo' function for a dummy class in FooNamespace and #include that in Bar.h, e.g.
//Dummy.h:
struct DummyClass
{
private:
DummyClass(){}
};
namespace FooNamespace
{
inline void foo(DummyClass& x); //purely to open up namespace
}
//Bar.h
#include "Dummy.h"
Is there any way around this, such that I can define bar and avoid having to create redundant code to open up FooNamespace in Bar?
My solution would be to get rid of the useless DefaultFooNamespace namespace. Put the default foo in the same namespace as the overloads, then bar just does:
using FooNamespace::foo;
foo(x);
The default foo is used if the caller hasn't included a definition of a more appropriate one for the type of x
I don't see a reason for the default foo to be in a separate namespace, especially because doing that requires a separate dummy definition to make bar valid code, when the same overload could serve both purposes.

creating methods that doesn't depend on a object

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;
}