Using-directive class static functions? - c++

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

Related

C++ method implementations: Can I avoid typing the class name each time?

When I have a C++ class MyClass in namespace mynamespace, I implement its methods as
void mynamespace::MyClass::method() { … }
I can wrap that in a namespace to shorten individual definitions to
namespace mynamespace {
void MyClass::method() { ... }
}
Is there a way to avoid having to retype MyClass:: as well so I can copy everything before the { to the header as a prototype more easily whenever the signature changes, without having to remove the MyClass:: every time?
I thought "a class is also a namespace, maybe I can do"
namespace mynamespace::MyClass {
void method() { ... }
}
but that complains that I was re-defining MyClass as a different thing. using mynamespace::MyClass; also didn't work (but would be bad anyway because how would I declare a standalone function anywhere below that line in that file if it worked).
Is there a solution to this, or is it simply not possible in C++?
No, the qualified class name must appear on any class member defined outside the class definition. (And there can only be one class definition, which is normally in a header file.)
The C++ Standard spells out this rule in [class.mfct]/4:
If the definition of a member function is lexically outside its class definition, the member function name shall be qualified by its class name using the ​::​ operator.
and similarly in [class.static.data]/2 for static data members.
You might abbreviate this qualification using preprocessor macros, but that would seriously harm legibility and is not a common practice.
There is no idiomatic way to avoid this. Even if you or someone else might come up with a "hack" (macro-based, for example), it would make the code less readable for everyone. The normal and expected way to write C++ is for the member functions to have the preceding MyClass:: when defined outside the class definition.
I would suggest to look for a tool that can update signatures between header and source file on command.
Or, as the comments suggest, provide the definitions of your functions right with the declaration inside the class definition (i.e. provide inline definitions). But that has its own disadvantages.
Using C++20 modules, you can implement a class in one file:
module myproject.mymodule;
namespace mynamespace {
export struct my_class {
auto my_method() -> int {
return 8;
}
};
}
Or export a whole namespace fragment:
export namespace mynamespace {
struct my_class {
auto my_method() -> int {
return 8;
}
};
auto also_exported() -> void {
// ...
}
}
Then, instead of including it, you can import that module:
import myproject.mymodule;
auto frob() -> void {
auto my_instance = mynamespace::my_class{};
}

Inline member do not need declaration

In C++ we have feature people do not think about much, like we can execute method of a class that uses method/member that has been declared later in class i.e.:
struct s{
foo() { foo1();}
foo1() { assert(0); }
};
int main() {
s s1; s1.foo();
}
I already know that compiler puts member definitions after class definition and it can be found so the order doesn't matter: Do class functions/variables have to be declared before being used?. What I was wondering is how it would look like if we would make methods inline and compiler will respect our request and make them really inline would it work then? Would compiler do any additional stuff to reorder whole class?

C++ class implementation namespace

I have files MyClass.hpp and MyClass.cpp
MyClass.hpp
class MyClass {
public:
void method1();
void method2();
};
MyClass.cpp
#include "MyClass.hpp"
void MyClass::method1() {
}
void MyClass::method2() {
}
I find it a little silly that I have to write out the MyClass:: every time I have to write a method implementation. Is there some sort of syntactic sugar that lets me just group all my implementation together?
Perhaps something like
namespace MyClass {
void method1() {
}
void method2() {
}
}
I don't mind using C++11 features, but I would like to stick with portable solutions.
EDIT:
I realize that the code above as written wouldn't work. I was just using it as an illustration of how I imagine some syntactic sugar would work to make things more convenient.
No, it is not possible.
The only way is to define your member functions directly inside the class definition, which makes them inline and may or may not be what you want.
Personally, I reckon having function definitions in source files is well worth having to type out a class name once in each.
No, there is no other-way. You have to repeat MyClass::
It is not possible to identify a method using namespace. In a namespace there can be several classes, non-member methods .... Since a class method can be defined in any source file (other than the header declaring the class itself), you have to specify which class a method belongs to while defining it.

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).

How do you create a static class in C++?

How do you create a static class in C++? I should be able to do something like:
cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
Assuming I created the BitParser class. What would the BitParser class definition look like?
If you're looking for a way of applying the "static" keyword to a class, like you can in C# for example, then you won't be able to without using Managed C++.
But the looks of your sample, you just need to create a public static method on your BitParser object. Like so:
BitParser.h
class BitParser
{
public:
static bool getBitAt(int buffer, int bitIndex);
// ...lots of great stuff
private:
// Disallow creating an instance of this object
BitParser() {}
};
BitParser.cpp
bool BitParser::getBitAt(int buffer, int bitIndex)
{
bool isBitSet = false;
// .. determine if bit is set
return isBitSet;
}
You can use this code to call the method in the same way as your example code.
Consider Matt Price's solution.
In C++, a "static class" has no meaning. The nearest thing is a class with only static methods and members.
Using static methods will only limit you.
What you want is, expressed in C++ semantics, to put your function (for it is a function) in a namespace.
Edit 2011-11-11
There is no "static class" in C++. The nearest concept would be a class with only static methods. For example:
// header
class MyClass
{
public :
static void myMethod() ;
} ;
// source
void MyClass::myMethod()
{
// etc.
}
But you must remember that "static classes" are hacks in the Java-like kind of languages (e.g. C#) that are unable to have non-member functions, so they have instead to move them inside classes as static methods.
In C++, what you really want is a non-member function that you'll declare in a namespace:
// header
namespace MyNamespace
{
void myMethod() ;
}
// source
namespace MyNamespace
{
void myMethod()
{
// etc.
}
}
Why is that?
In C++, the namespace is more powerful than classes for the "Java static method" pattern, because:
static methods have access to the classes private symbols
private static methods are still visible (if inaccessible) to everyone, which breaches somewhat the encapsulation
static methods cannot be forward-declared
static methods cannot be overloaded by the class user without modifying the library header
there is nothing that can be done by a static method that can't be done better than a (possibly friend) non-member function in the same namespace
namespaces have their own semantics (they can be combined, they can be anonymous, etc.)
etc.
Conclusion: Do not copy/paste that Java/C#'s pattern in C++. In Java/C#, the pattern is mandatory. But in C++, it is bad style.
Edit 2010-06-10
There was an argument in favor to the static method because sometimes, one needs to use a static private member variable.
I disagree somewhat, as show below:
The "Static private member" solution
// HPP
class Foo
{
public :
void barA() ;
private :
void barB() ;
static std::string myGlobal ;
} ;
First, myGlobal is called myGlobal because it is still a global private variable. A look at the CPP source will clarify that:
// CPP
std::string Foo::myGlobal ; // You MUST declare it in a CPP
void Foo::barA()
{
// I can access Foo::myGlobal
}
void Foo::barB()
{
// I can access Foo::myGlobal, too
}
void barC()
{
// I CAN'T access Foo::myGlobal !!!
}
At first sight, the fact the free function barC can't access Foo::myGlobal seems a good thing from an encapsulation viewpoint... It's cool because someone looking at the HPP won't be able (unless resorting to sabotage) to access Foo::myGlobal.
But if you look at it closely, you'll find that it is a colossal mistake: Not only your private variable must still be declared in the HPP (and so, visible to all the world, despite being private), but you must declare in the same HPP all (as in ALL) functions that will be authorized to access it !!!
So using a private static member is like walking outside in the nude with the list of your lovers tattooed on your skin : No one is authorized to touch, but everyone is able to peek at. And the bonus: Everyone can have the names of those authorized to play with your privies.
private indeed...
:-D
The "Anonymous namespaces" solution
Anonymous namespaces will have the advantage of making things private really private.
First, the HPP header
// HPP
namespace Foo
{
void barA() ;
}
Just to be sure you remarked: There is no useless declaration of barB nor myGlobal. Which means that no one reading the header knows what's hidden behind barA.
Then, the CPP:
// CPP
namespace Foo
{
namespace
{
std::string myGlobal ;
void Foo::barB()
{
// I can access Foo::myGlobal
}
}
void barA()
{
// I can access myGlobal, too
}
}
void barC()
{
// I STILL CAN'T access myGlobal !!!
}
As you can see, like the so-called "static class" declaration, fooA and fooB are still able to access myGlobal. But no one else can. And no one else outside this CPP knows fooB and myGlobal even exist!
Unlike the "static class" walking on the nude with her address book tattooed on her skin the "anonymous" namespace is fully clothed, which seems quite better encapsulated AFAIK.
Does it really matter?
Unless the users of your code are saboteurs (I'll let you, as an exercise, find how one can access to the private part of a public class using a dirty behaviour-undefined hack...), what's private is private, even if it is visible in the private section of a class declared in a header.
Still, if you need to add another "private function" with access to the private member, you still must declare it to all the world by modifying the header, which is a paradox as far as I am concerned: If I change the implementation of my code (the CPP part), then the interface (the HPP part) should NOT change. Quoting Leonidas : "This is ENCAPSULATION!"
Edit 2014-09-20
When are classes static methods are actually better than namespaces with non-member functions?
When you need to group together functions and feed that group to a template:
namespace alpha
{
void foo() ;
void bar() ;
}
struct Beta
{
static void foo() ;
static void bar() ;
};
template <typename T>
struct Gamma
{
void foobar()
{
T::foo() ;
T::bar() ;
}
};
Gamma<alpha> ga ; // compilation error
Gamma<Beta> gb ; // ok
gb.foobar() ; // ok !!!
Because, if a class can be a template parameter, a namespaces cannot.
You can also create a free function in a namespace:
In BitParser.h
namespace BitParser
{
bool getBitAt(int buffer, int bitIndex);
}
In BitParser.cpp
namespace BitParser
{
bool getBitAt(int buffer, int bitIndex)
{
//get the bit :)
}
}
In general this would be the preferred way to write the code. When there's no need for an object don't use a class.
If you're looking for a way of applying the "static" keyword to a class, like you can in C# for example
static classes are just the compiler hand-holding you and stopping you from writing any instance methods/variables.
If you just write a normal class without any instance methods/variables, it's the same thing, and this is what you'd do in C++
Can I write something like static class?
No, according to the C++11 N3337 standard draft Annex C 7.1.1:
Change: In C ++, the static or extern specifiers can only be applied to names of objects or functions.
Using these specifiers with type declarations is illegal in C ++. In C, these specifiers are ignored when used
on type declarations. Example:
static struct S { // valid C, invalid in C++
int i;
};
Rationale: Storage class specifiers don’t have any meaning when associated with a type. In C ++, class
members can be declared with the static storage class specifier. Allowing storage class specifiers on type
declarations could render the code confusing for users.
And like struct, class is also a type declaration.
The same can be deduced by walking the syntax tree in Annex A.
It is interesting to note that static struct was legal in C, but had no effect: Why and when to use static structures in C programming?
In C++ you want to create a static function of a class (not a static class).
class BitParser {
public:
...
static ... getBitAt(...) {
}
};
You should then be able to call the function using BitParser::getBitAt() without instantiating an object which I presume is the desired result.
As it has been noted here, a better way of achieving this in C++ might be using namespaces. But since no one has mentioned the final keyword here, I'm posting what a direct equivalent of static class from C# would look like in C++11 or later:
class BitParser final
{
public:
BitParser() = delete;
static bool GetBitAt(int buffer, int pos);
};
bool BitParser::GetBitAt(int buffer, int pos)
{
// your code
}
You 'can' have a static class in C++, as mentioned before, a static class is one that does not have any objects of it instantiated it. In C++, this can be obtained by declaring the constructor/destructor as private. End result is the same.
In Managed C++, static class syntax is:-
public ref class BitParser abstract sealed
{
public:
static bool GetBitAt(...)
{
...
}
}
... better late than never...
Unlike other managed programming language, "static class" has NO meaning in C++. You can make use of static member function.
This is similar to C#'s way of doing it in C++
In C# file.cs you can have private var inside a public function.
When in another file you can use it by calling the namespace with the function as in:
MyNamespace.Function(blah);
Here's how to imp the same in C++:
SharedModule.h
class TheDataToBeHidden
{
public:
static int _var1;
static int _var2;
};
namespace SharedData
{
void SetError(const char *Message, const char *Title);
void DisplayError(void);
}
SharedModule.cpp
//Init the data (Link error if not done)
int TheDataToBeHidden::_var1 = 0;
int TheDataToBeHidden::_var2 = 0;
//Implement the namespace
namespace SharedData
{
void SetError(const char *Message, const char *Title)
{
//blah using TheDataToBeHidden::_var1, etc
}
void DisplayError(void)
{
//blah
}
}
OtherFile.h
#include "SharedModule.h"
OtherFile.cpp
//Call the functions using the hidden variables
SharedData::SetError("Hello", "World");
SharedData::DisplayError();
One (of the many) alternative, but the most (in my opinion) elegant (in comparison to using namespaces and private constructors to emulate the static behavior), way to achieve the "class that cannot be instantiated" behavior in C++ would be to declare a dummy pure virtual function with the private access modifier.
class Foo {
public:
static int someMethod(int someArg);
private:
virtual void __dummy() = 0;
};
If you are using C++11, you could go the extra mile to ensure that the class is not inherited (to purely emulate the behavior of a static class) by using the final specifier in the class declaration to restrict the other classes from inheriting it.
// C++11 ONLY
class Foo final {
public:
static int someMethod(int someArg);
private:
virtual void __dummy() = 0;
};
As silly and illogical as it may sound, C++11 allows the declaration of a "pure virtual function that cannot be overridden", which you can use alongside declaring the class final to purely and fully implement the static behavior as this results in the resultant class to not be inheritable and the dummy function to not be overridden in any way.
// C++11 ONLY
class Foo final {
public:
static int someMethod(int someArg);
private:
// Other private declarations
virtual void __dummy() = 0 final;
}; // Foo now exhibits all the properties of a static class
There is no such thing as a static class in C++. The closest approximation is a class that only contains static data members and static methods.
Static data members in a class are shared by all the class objects as there is only one copy of them in memory, regardless of the number of objects of the class.
A static method of a class can access all other static members ,static methods and methods outside the class
One case where namespaces may not be so useful for achieving "static classes" is when using these classes to achieve composition over inheritance. Namespaces cannot be friends of classes and so cannot access private members of a class.
class Class {
public:
void foo() { Static::bar(*this); }
private:
int member{0};
friend class Static;
};
class Static {
public:
template <typename T>
static void bar(T& t) {
t.member = 1;
}
};
class A final {
~A() = delete;
static bool your_func();
}
final means that a class cannot be inherited from.
delete for a destructor means that you can not create an instance of such a class.
This pattern is also know as an "util" class.
As many say the concept of static class doesn't exist in C++.
A canonical namespace that contains static functions preferred as a solution in this case.