May I declare "using namespace" inside a C++ class? - c++

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.

Related

C++ combining namespaces

I have some shared files that I want to use between two programs A and B that have the same compile target and are very identical.
So, I tried to separate them into two namespaces and create a shared namespace for the shared files
Interfaces.h
namespace ns_s {
class SomeClass;
class IFoo {
virtual void bar(SomeClass*) = 0;
};
}
SomeHeaderinA.h
#include "Interfaces.h"
namespace ns_a {
using namespace ns_s;
class Foo : public IFoo {
virtual void bar(SomeClass* p) override { ... }
};
}
However the compiler is complaining now that my member function bar does not override anything, so it seems to not see the interface implementation.
Why is that the case? And why does the compiler not already complain about a missing class IFoo?
EDIT:
Looks like I missed an essential part that contributes to the problem. I pre-declared a class that is a parameter of the interface method. Now that I ahve a pre-declaration in namespace shared and an actual declaration in namsepace A those things are not the same anymore.
Is there a good way to fix this? Only a small subset of interfaces have arguments that are defined in one or the other namesapce (A or B), so I could leave different implementations in each of them, but it would be nice to have it all in the shared space if possible in a clean fashion.
Here is a link
http://coliru.stacked-crooked.com/a/79fa58e50e7b8637
Problem
As shown in the linked code, the problem is caused by SomeClass.
The line
class SomeClass{};
declares and defines SomeClass in namespace ns_a. It does not define SomeClass in namespace ns_s.
The declaration of class ns_s::IFoo::bar uses ns_s::SomeClass.
The declaration of class ns_a::IFoo::bar uses ns_a::SomeClass.
That's the override is an error.
Solution
You can fix it by:
Removing the definition of SomeClass from ns_a, or
Using ns_s::SomeClass in the declaration of ns_a::IFoo::bar.
namespace ns_a {
using namespace ns_s;
class Foo : public IFoo {
virtual void bar(SomeClass* p) override {}
};
}
or
namespace ns_a {
using namespace ns_s;
class SomeClass{};
class Foo : public IFoo {
virtual void bar(ns_s::SomeClass* p) override {}
};
}

Standard way to control symbol visibility

Using C and plain functions in C++, I can prevent the functions' symbols to be exported by using static keyword:
static int foo(int a, int b) { /* ... */ }
But in a class, defining a function as static has a completely different meaning. Is there a way to ensure the compiler that my whole class will be used only within module, and there is no need to export any of its methods' symbols?
Use an anonymous namespace.
namespace
{
class C
{
C() {}
void f() {}
};
void f();
}
class ExportedClass
{
ExportedClass() {}
void f() {}
};
void exportedFunction() {}
As you can see, you should do this for normal functions, too. The usage of static for this is discouraged.
You can use the anonymous namespace. For example,
// file foo.cc
namespace {
int symbol1 = 0;
struct auxiliary { /* ... */ } symbol2;
}
void foo(int x)
{
// uses symbol1 and symbol2
}
when symbol1 and symbol2 are not 'visible'.
Depending on what you want and why you are doing it you could move the class into the .cpp file. This works for example if you are implementing a library. Have a look at the discussion at Putting class declaration in .cpp file
To be more specific your class should go in it's own separate translation unit away from main and away from classes outside of your module.

Is there a need to set up a class for one or several functions in C++

I feel confused with whether there is a need to set up a class for one or several functions. I give the following example to make my point clear:
file1.h
void Fun1();
void Fun2();
file1.cpp
void Fun1() {}
void Fun2() {}
As you can see we have two functions here, and people using these functions just need to include the header file and then call them. Then, I also have the choice of setting up a class without any member variables insider but only for these two functions (suppose these two functions are closely related):
file1.h
class Operation
{
Operation() {};
~Operation() {};
void Fun1();
void Fun2();
};
file1.cpp
void Operation::Fun1() {};
void Operation::Fun2() {};
Then my question is which practice is better and why. Thanks.
You should use a dedicated namespace
file1.h:
namespace MyDedicatedNameSpace
{
void Fun1();
void Fun2();
}
file1.cpp:
void MyDedicatedNameSpace::Fun1() {}
void MyDedicatedNameSpace::Fun2() {}
Or if you want to use a class, you should set these functions as static:
file1.h:
class Operation
{
public:
static void Fun1();
static void Fun2();
};
file1.cpp:
void Operation::Fun1() {};
void Operation::Fun2() {};
You don't "have to" put them in a class, you can go for both implementations. It's mostly a design preference. Java coders are used to putting those functions as static functions of a utility class, but in C++ you don't have to, although some people do.
If your concern is just encapsulation of those functions in a specific context, you might also consider putting them in namespaces.
There should be a reason you want to put them in one class.
If it's just for grouping, namespace better suits for this role.
file1.h
namespace Operation
{
void Fun1();
void Fun2();
};
file1.cpp
namespace Operation
{
void Fun1(){};
void Fun2(){};
};
P.S. If for some reason you would still prefer to use class, make functions static at least, so you wouldn't need to create an instance of this class.
file1.h
class Operation
{
public:
static void Fun1();
static void Fun2();
};
file1.cpp
void Operation::Fun1() {};
void Operation::Fun2() {};
Since you asked specifically about C++, the most correct answer would be to namespace them:
file1.h:
namespace MyNamespace
{
void Fun1();
void Fun2();
}
file1.cpp:
namespace MyNamespace
{
void Fun1() {}
void Fun2() {}
}
Then to use them you would simply call MyNamespace::Fun1() etc.
As I started out saying, this is most correct for C++.
If you were writing this for C, or mixed C/C++ it should be noted that C does not support namespaces. So in that case making them static functions of a class would be a better organizational route.
file1.h
class MyClass
{
public:
static void Fun1();
static void Fun2();
};
file1.c
void MyClass::Fun1() { }
void MyClass::Fun2() { }
NOTE: if you are doing mixed programming you should consider making it easier to include, but that's beyond the scope of this question.

Separate class for a namespace advisable?

I have a couple functions that I want to use in many different classes. I have a couple classes that are derived from one base class and so tried to make it so that the base class held the functions and then the child classes could just call them. This seemed to cause linking errors, and so following advice from this question (Advantages of classes with only static methods in C++) I decided to give namespaces a swing, but the only file that is included by every header/file is resource.h, and I don't want to put a namespace for my functions in there as it seems to specialised to mess with.
My question is, how do I make a class that only includes a namespace, or the functions I want to use, so that I can just include this class and use the functions as desired?
Thank you in advance for the help, the answers I've found on the internet only focus on one file, not multiple files like I'm hoping to address :)
You seem confused about how namespaces are used. Here are some things to keep in mind when working with namespaces:
You create a namespace using the syntax namespace identifier { /* stuff */ }. Everything between the { } will be in this namespace.
You cannot create a namespace inside a user-defined type or function.
A namespace is an open group construct. This means you can add more stuff into this namespace later on in some other piece of code.
Namespaces aren't declared unlike some of the other language constructs.
If you want certain classes and/or functions inside a namespace scope, enclose it with the namespace syntax in the header of where it's defined. Modules using those classes will see the namespace when the headers get #include'd.
For example, in your Entity.h you might do:
// Entity.h
#pragma once
namespace EntityModule{
class Entity
{
public:
Entity();
~Entity();
// more Entity stuff
};
struct EntityFactory
{
static Entity* Create(int entity_id);
};
}
inside your main.cpp you access it like this:
#include "Entity.h"
int main()
{
EntityModule::Entity *e = EntityModule::EntityFactory::Create(42);
}
If you also want Player to be inside this namespace then just surround that with namespace EntityModule too:
// Player.h
#pragma once
#include "Entity.h"
namespace EntityModule{
class Player : public Entity
{
// stuff stuff stuff
};
}
This works because of point #3 above.
If for some reason you feel you need to create a namespace inside a class, you can simulate this to an extent using nested classes:
class Entity
{
public:
struct InnerEntity
{
static void inner_stuff();
static int more_inner_stuff;
private:
InnerEntity();
InnerEntity(const InnerEntity &);
};
// stuff stuff stuff
};
Some important differences and caveats doing it this way though:
Everything is qualified with static to indicate there's no specific instance associated.
Can be passed as a template parameter.
Requires a ; at the end.
You can't create a convenient shorthand with abusing namespace Entity::InnerEntity;. But perhaps this is a good thing.
Unlike namespaces, class and struct are closed constructs. That means you cannot extend what members it contains once defined. Doing so will cause a multiple definition error.
You can put anything in a namespace, but you can't put namespaces inside things ( that's not a very formal way of saying it but I hope you get what I mean.
Valid
namespace foospace
{
class foo
{
public :
foo();
~foo();
void eatFoo();
};
}
Invalid
namespace foospace
{
class foo
{
public :
foo();
~foo();
namespace eatspace
{
void eatFoo();
}
};
}
I'm not 100% certain that the second example wouldn't compile, but regardless, you shouldn't do it.
Now, from your comments it sounds like you want something like this :
In the file Entity.h, your entity class definition :
namespace EntitySpace
{
class Entity
{
public :
Entity();
~Entity();
};
}
In the file Player.h
#include "Entity.h"
namespace EntitySpace
{
class Player : public Entity
{
public :
Player();
~Player();
};
}
In the file main.cpp
#include "Player.h"
int main()
{
EntitySpace::Player p1;
EntitySpace::Player p2;
}
So you call upon Player in the EntitySpace namespace. Hope this answers what you were asking.

Is pimpl compatible with anonymous namespaces?

I am trying to use the pimpl pattern and define the implementation class in an anonymous namespace. Is this possible in C++? My failed attempt is described below.
Is it possible to fix this without moving the implementation into a namespace with a name (or the global one)?
class MyCalculatorImplementation;
class MyCalculator
{
public:
MyCalculator();
int CalculateStuff(int);
private:
MyCalculatorImplementation* pimpl;
};
namespace // If i omit the namespace, everything is OK
{
class MyCalculatorImplementation
{
public:
int Calculate(int input)
{
// Insert some complicated calculation here
}
private:
int state[100];
};
}
// error C2872: 'MyCalculatorImplementation' : ambiguous symbol
MyCalculator::MyCalculator(): pimpl(new MyCalculatorImplementation)
{
}
int MyCalculator::CalculateStuff(int x)
{
return pimpl->Calculate(x);
}
No, the type must be at least declared before the pointer type can be used, and putting anonymous namespace in the header won't really work. But why would you want to do that, anyway? If you really really want to hide the implementation class, make it a private inner class, i.e.
// .hpp
struct Foo {
Foo();
// ...
private:
struct FooImpl;
boost::scoped_ptr<FooImpl> pimpl;
};
// .cpp
struct Foo::FooImpl {
FooImpl();
// ...
};
Foo::Foo() : pimpl(new FooImpl) { }
Yes. There is a work around for this. Declare the pointer in the header file as void*, then use a reinterpret cast inside your implementation file.
Note: Whether this is a desirable work-around is another question altogether. As is often said, I will leave that as an exercise for the reader.
See a sample implementation below:
class MyCalculator
{
public:
MyCalculator();
int CalculateStuff(int);
private:
void* pimpl;
};
namespace // If i omit the namespace, everything is OK
{
class MyCalculatorImplementation
{
public:
int Calculate(int input)
{
// Insert some complicated calculation here
}
private:
int state[100];
};
}
MyCalculator::MyCalculator(): pimpl(new MyCalculatorImplementation)
{
}
MyCalaculator::~MyCalaculator()
{
// don't forget to cast back for destruction!
delete reinterpret_cast<MyCalculatorImplementation*>(pimpl);
}
int MyCalculator::CalculateStuff(int x)
{
return reinterpret_cast<MyCalculatorImplementation*>(pimpl)->Calculate(x);
}
No, you can't do that. You have to forward-declare the Pimpl class:
class MyCalculatorImplementation;
and that declares the class. If you then put the definition into the unnamed namespace, you are creating another class (anonymous namespace)::MyCalculatorImplementation, which has nothing to do with ::MyCalculatorImplementation.
If this was any other namespace NS, you could amend the forward-declaration to include the namespace:
namespace NS {
class MyCalculatorImplementation;
}
but the unnamed namespace, being as magic as it is, will resolve to something else when that header is included into other translation units (you'd be declaring a new class whenever you include that header into another translation unit).
But use of the anonymous namespace is not needed here: the class declaration may be public, but the definition, being in the implementation file, is only visible to code in the implementation file.
If you actually want a forward declared class name in your header file and the implementation in an anonymous namespace in the module file, then make the declared class an interface:
// header
class MyCalculatorInterface;
class MyCalculator{
...
MyCalculatorInterface* pimpl;
};
//module
class MyCalculatorInterface{
public:
virtual int Calculate(int) = 0;
};
int MyCalculator::CalculateStuff(int x)
{
return pimpl->Calculate(x);
}
namespace {
class MyCalculatorImplementation: public MyCalculatorInterface {
...
};
}
// Only the ctor needs to know about MyCalculatorImplementation
// in order to make a new one.
MyCalculator::MyCalculator(): pimpl(new MyCalculatorImplementation)
{
}
markshiz and quamrana provided the inspiration for the solution below.
class Implementation, is intended to be declared in a global header file and serves as a void* for any pimpl application in your code base. It is not in an anonymous/unnamed namespace, but since it only has a destructor the namespace pollution remains acceptably limited.
class MyCalculatorImplementation derives from class Implementation. Because pimpl is declared as std::unique_ptr<Implementation> there is no need to mention MyCalculatorImplementation in any header file. So now MyCalculatorImplementation can be implemented in an anonymous/unnamed namespace.
The gain is that all member definitions in MyCalculatorImplementation are in the anonymous/unnamed namespace. The price you have to pay, is that you must convert Implementation to MyCalculatorImplementation. For that purpose a conversion function toImpl() is provided.
I was doubting whether to use a dynamic_cast or a static_cast for the conversion. I guess the dynamic_cast is the typical prescribed solution; but static_cast will work here as well and is possibly a little more performant.
#include <memory>
class Implementation
{
public:
virtual ~Implementation() = 0;
};
inline Implementation::~Implementation() = default;
class MyCalculator
{
public:
MyCalculator();
int CalculateStuff(int);
private:
std::unique_ptr<Implementation> pimpl;
};
namespace // Anonymous
{
class MyCalculatorImplementation
: public Implementation
{
public:
int Calculate(int input)
{
// Insert some complicated calculation here
}
private:
int state[100];
};
MyCalculatorImplementation& toImpl(Implementation& impl)
{
return dynamic_cast<MyCalculatorImplementation&>(impl);
}
}
// no error C2872 anymore
MyCalculator::MyCalculator() : pimpl(std::make_unique<MyCalculatorImplementation>() )
{
}
int MyCalculator::CalculateStuff(int x)
{
return toImpl(*pimpl).Calculate(x);
}