C++ Namespace 'using' declarative for a class' enum - c++

I have a good understanding of how the C++ 'using' declaration and directive work. However, I'm stumped on this... Maybe it's not possible? I want to avoid having to quality my enum variables:
namespace Foo {
class MyClass {
public:
enum MyEnum { X, Y, Z };
}
}
And now, from outside that namespace, I would like to be able to do things like:
using Foo::MyClass.MyEnum;
MyEnum letter = MyEnum::x;
But apparently that's not the way to do it? I'm betting this is possible, but my notation is wrong... I also tried using Foo::MyClass::MyEnum, but then the compiler thinks Foo::MyClass is a namespace.
Added: As you can see, it becomes annoying having to fully declare everything...
Foo::MyClass::MyEnum value = Foo::MyClass::X;

This doesn't answer your question directly, but if you want to economize keystrokes you could try using a typedef instead.
typedef Foo::MyClass::MyEnum MyClassEnum;
By the way, it looks like your question has been asked on Stack Overflow before. From the answer to that question:
A class does not define a namespace,
therefore "using" isn't applicable
here.

C++03 does not support fully qualifying enum types, but it's an MSVC extension. C++0x will make this Standard, and I believe that you can using an enum in C++0x. However, in C++03, I don't believe that your problem can be solved.

I got the following to compile, after messing around a lot. I think that it will be the closest you can get without typedef'ing.
namespace Foo {
class MyClass {
public:
enum MyEnum { X, Y, Z };
};
};
namespace Foo2 {
using Foo::MyClass;
class AnotherClass {
public:
AnotherClass(){
MyClass::MyEnum value = MyClass::X;
}
};
};
int main(){
return 1;
}
You could also use MyClass as a base class, but I am doubting that's something you want to do.
namespace Foo2 {
using namespace Foo;
class AnotherClass : public MyClass{
public:
AnotherClass(){
MyEnum value = X;
}
};
};
This also has some good info.
namespaces for enum types - best practices

Related

MISRA C++ 2008 Rule 7–3–1 and Forward Declaration

Let's say I wanted to forward declare CLibraryStruct in my MyClass.hpp
class CLibraryStruct;
class MyClass {
private:
CLibraryStruct *cLibStr;
};
At the same time I also wanted to be compliant with MISRA C++ 2008 Rule 7–3–1:
The global namespace shall only contain main, namespace declarations and extern "C" declarations.
I obviously can't use anonymous namespaces here, but I think I could try this:
class MyClass {
private:
class CLibraryStruct *cLibStr;
};
Or this:
#include "CLibrary.h"
class MyClass {
private:
CLibraryStruct *cLibStr;
};
Would you be so kind as to help me out and explain to me which would be a better choice (or suggest an alternative)?

Why does the compiler not complain when the struct keyword is reused in a function, with a variable declaration?

Sorry about the vague question, I was unsure of how to be specific while being concise. I noticed the following behaviour when looking at a colleague's code, and I don't understand why the compiler (GCC 4.8.2) doesn't complain. Here is a trivial example:
#include <iostream>
using namespace std;
struct mystruct {
int val;
};
int main()
{
struct mystruct x; //What is the compiler doing here?
/* Do something with x here */
return(0);
}
How is the compiler treating the line struct mystruct x;? If it treated it as a declaration of some local struct called mystruct and initialisation of an instance called x, why am I allowed to treat x as an instance of the mystruct defined in the global scope?
My other thought was that it might be acting like a forward declaration, but I wasn't aware that one could declare an instance of a class at the same time as making a forward declaration. Is that simply what's happening here, though (and it's effectively doing nothing other than declaring the variable, since mystruct is already defined)?
The compiler doesn't complain because there is nothing wrong with your code. You have done exactly what you have described. You have defined x to be a variable of type mystruct.
You may be unfamiliar with this form, but in C, it is the only way to declare variables to have a struct type. It's less common in C++ because the struct keyword was made optional in this context; however, C++ maintains compatibility with the traditional C syntax.
It's c syntax and as such valid for c++.
In c you would be required to use typedef if you wished to drop the struct keyword in the declaration.
Indeed if you declare the the typedef'd and untypedef'd name, you can initialise using either syntax.
e.g.
typedef struct mystruct {
int val;
} mystruct;
int main()
{
mystruct x;
struct mystruct x2;
/* Do something with x here */
return(0);
}
For c++ The use of typedef in the declaration of a struct is not required and so the use of struct in the declaration of an instance is optional, supported mainly for legacy reasons.
If you find yourself working on a cross C/C++ code base it will be useful to understand how both can play together happily like this.
struct mystruct is synonymous with mystruct, assuming that such a struct has already been declared.
The word struct in this context is
Completely optional in C++
Potentially a readability aid, if you're prone to think that it's an enum or some other type
A carryover from the C language, where it would have been required, given similar code.

C++ Should I fully qualified my variable type?

I am trying to write lines of code fitting under 80 columns maximum. Thus, I wonder if fully qualifying my variable type is really mandatory ? Assuming the following implementation:
//Baz.h
namespace loggingapi {
namespace attributes {
class Baz {};
}} // namespaces
// Bar.h
namespace loggingapi {
namespace attributes {
class Baz; // forward declare Baz.
}
class Biz {
int f(Baz* b);
};
} // namespaces
To declare my function parameter type, there are multiple ways ?
a) int f(Baz* b);
b) OR int f(attributes::Baz* b);
c) OR int f(loggingapi::attributes::Baz* b);
d) OR int f(::loggingapi::attributes::Baz* b);
In the list above, which definition(s) is/are clearer/ambiguous for the compilers ?
NOTE: You must assume the namespace/parameter/class/function names CANNOT be shortened in the following implementation.
Variant e ?
namespace loggingapi {
namespace attributes {
class Baz; // forward declare Baz.
}
class Biz {
typedef attributes::Baz Baz;
// C++ 11 alternative
// using Baz = attributes::Baz;
int f(Baz* b);
}
} // namespaces
Do not forget what aliasing can do for you...
I would go with the b) variant. My reasons are as follows:
We assume that the developer knows in what namespace he is now. So when looking at the class Biz, the developer should know that this class is in the loggingapi namespace, therefore, there's no need to explicitly state it.
The a) variant, on the other hand, isn't clear enough, because we should indicate that Baz and Biz are actually in different namespaces. Also, it is not going compile, because the compiler will look for Baz in the loggingapi namespace, and it isn't there.
You should choose (b). It's more flexible. If you decide to move or (gasp) cut and paste f and it's related types to a new namespace or project then using (b) ensures that the structure of the declarations remains internally consistent.
You can choose to add, remove or rename outer wrapping namespaces without affecting the enclosed code.
In h-file it is better to use fully qualified names, to prevent possible ambiguity in a client code. In .cpp file you can use short notation, if you prefer this, as long as there is no name clash.
If a compiler has some ambiguity it will definitely report an error.
I believe the question should be with respect to the human reader, which is quite subjective.
The naming convention depends on
Pre-decided coding style
Where you are declaring the function f()
There is no clear choice over another. I would prefer that, if both entities are belonging to same namespace then I will omit at least that part from the name:
namespace loggingapi {
namespace attributes {
class Baz; // forward declare Baz.
}
class Biz {
int f(attribute::Baz* b);
}; // ^^^^^^^^^^^^^
}

Using-directive class static functions?

I am using an API that has a lot of functions in a class named TCODConsole as static functions. Now I thought that it was in a namespace, so I wrote: using namespace TCODConsole;. Then I found out that TCODConsole ain't a namespace, but a class.
Is there a way to import those functions in a similar way as you would use using namespace?
No, there is no shortcut way to call myStaticFun() instead of MyClass::myStaticFun(). You cannot do that with class. It's a class, not a namespace. But you can write something like a wrapper. That is you will add functions with same name and call the static methods from that functions. Something like this:
class MyClass {
static void fun();
};
void fun() {
MyClass::fun();
}
// call it
fun();
Not a very good way. Personally I think it is better to stick with the class instead of doing this.
Though I may misunderstand the question,
if shortening the qualification is the objective,
does typedefing like the following meet the purpose?
struct TCODConsole {
static void f();
static void g();
};
int main() {
typedef TCODConsole T;
T::f();
T::g();
}
Alternatively, if the class TCODConsole can be instantiated,
since static member function can be called with the same form as
non-static member function, the following code might meet the purpose:
int main() {
TCODConsole t;
t.f();
t.g();
}
I can't think of a clean way to do it, but I can think of a kinda ugly hack that will work, as long as the code using it is part of a class (and if TCODConsole really contains only static member functions). Let's say you are bar(), a member function of the class Foo, and you want to call a function baz() which is a static member of TCODConsole without fully-qualifying it. What you can do is to privately derive Foo from TCODConsole:
class Foo : private TCODConsole
{
void bar()
{
baz();
}
};
Yeah, that's ugly. :(
If you want to use Boost.PP (the Boost Preprocessor macro library - you don't need to compile or include anything else from Boost to use it), you can probably make a less ugly but quite a bit more convoluted macro which will "import" these functions for you, by wrapping them with inline functions inside another namespace (which you can then import at will). It would still require you to explicitly specify the name each of the functions you want to "import", so your code (minus the macro) will look something like this:
namespace TCODStatic
{
IMPORT_FROM_TCOD(foo)
IMPORT_FROM_TCOD(bar)
IMPORT_FROM_TCOD(baz)
IMPORT_FROM_TCOD(spaz)
}
and then you'll be able to write using namespace TCODStatic; anywhere you want.
Short answer: not without using macros. There is no mechanism in the C++ language proper to do something like this:
class A
{
public:
static void foo();
};
// ...
using A;
foo();
You could use a macro to build these expressions for you:
#define FOO() (A::foo())
FOO();
I would discourage this however, because it can become a maintennence nightmare is you make extensive use of such macros. You end up with code like this:
FOO();
BAR();
SUPERGIZMO(a, b, c);
...where none of these things are defined as first-class names anywhere in the program. You've lost all type checking, the code uses a "secret language" that only you know, and it becomes difficult to debug, extend and fix.
EDIT:
You could write a kind of bridge. Like this:
class FooBar
{
public:
static void gizmo();
};
namespace Foo
{
void gizmo() { FooBar::gizmo(); };
};
using namespace Foo;
gizmo();

Preferred namespace syntax for source files

Assuming a class called Bar in a namespace called foo, which syntax do you prefer for your source (.cpp/.cc) file?
namespace foo {
...
void Bar::SomeMethod()
{
...
}
} // foo
or
void foo::Bar::SomeMethod()
{
...
}
I use namespaces heavily and prefer the first syntax, but when adding code using the Visual Studio Class Wizard (WM_COMMAND handlers, etc.) the auto-generated code uses the second. Are there any advantages of one syntax over the other?
I would decline the first (edit : question changed, the first is what i prefer too now). Since it is not clear where Bar refers to from only looking at the function definition. Also, with your first method, slippy errors could show up:
namespace bar {
struct foo { void f(); };
}
namespace baz {
struct foo { void f(); };
}
using namespace bar;
using namespace baz;
void foo::f() { // which foo??
}
Because it looks in the current scope (there it is the global scope), it finds two foo's, and tells you the reference to it is ambiguous.
Personally i would do it like this:
namespace foo {
void Bar::SomeMethod() {
// something in here
}
}
It's also not clear from only looking at the definition of SomeMethod to which namespace it belongs, but you have a namespace scope around it and you can easily look it up. Additionally, it is clear now that Bar refers to namespace foo.
The second way you show would be too much typing for me actually. In addition, the second way can cause confusion among new readers of your code: Is foo the class, and Bar a nested class of it? Or is foo a namespace and Bar the class?
I prefer an option not listed:
namespace foo {
void Bar::SomeMethod()
{
...
}
} // foo namespace
Unlike option one, this makes it obvious your code belongs in the foo namespace, not merely uses it. Unlike option two, it saves lots of typing. Win-win.
I'd rather go for the first case, where namespaces are explicitly marked:
namespace TheNamespace {
void TheClass::TheMethod() {
// code
}
}
The reason is that it is clear from that syntax that TheClass is a class and TheNamespace is a namespace (not so obvious by any other names). If the code were
void TheNamespace::TheClass::TheMethod() {
// code
}
then a reader does not clearly see whether TheNamespace is a namespace, or a class with an inside class by the name of TheClass.
class TheClass1
{
class TheClass2
{
void TheMethod();
}
};
void TheClass1::TheClass2::TheMethod() {
// code
}
I tend to avoid the 'using' statement, and even then the example by litb with two classes in two different namespaces will make both the compiler and the programmer confused and should be avoided.
I think it depends on each case. If it's a 3rd party library that's similar to your own code, and you want to avoid confusion in the code, then specifying the full namespace at each occurance may be beneficial. But other than that, less code is generally better (unless it becomes unclear).