C++ getting rid of Singletons: alternative to functors and static methods - c++

My noble quest is to get rid of singletons and static classes.
Background:
I have the following structures:
CmdFrequently instantiated object, it holds a name of the command (string), and functor to the static method of any class as a pointer.It is typically created in main classes such as Input, Console, Render, etc. and refers to methods within the class that it is created in, giving a runtime verbal interface to those methods.Cmds also interpret parameters in a form of a string array, where first argument is the name of the Cmd, and all consecutive strings are direct arguments for the static method being invoked. The argument count and argument array are stored in Commander, and changed before each Cmd call.
CommanderCommander is used to interpret string commands (which may come directly, or through Console) and it executes the Cmd which was stored in the buffer as a string (by invoking it's functor).
Problem:
Problem is that I am attempting to get rid of all the static classes (which I now turned into singletons for testing), and I am making the system fully modular and loosely coupled. This in turn prevents me from having static calls which Cmds could point to.
First instinct was to change the functor from a typedef into a template class, which would store an object and method, but it looks very messy and complex, and I personally am not comfortable going from:
Cmd::create("toggleconsole", Console::toggle);
To:
Cmd::create("toggleconsole", new FunctorObject<Console>(&Console::get(), &Console::toggle));
The final Cmd creation looks very obscure and misleading as to who is in charge of the Functor deallocation.
I am also in the process of moving Cmd creation from a static method call, into the Commander class, so it would look like commander.createCmd("command_name", ...); instead of Cmd::create("command_name",...); This is because Commander is no longer going to be static (or singleton), so all commands which it handles must belong to it.
I am, however, at a complete loss as to what my options/alternatives are to register Cmds, and maintain the loose coupling by allowing string commands to be issued to the Commander.
I have considered making each of the main classes derive from a CmdListener class, which would register the object with the Commander upon creation, and then during execution pass a command to all registered objects which overwrote the "onCmd(const Cmd &command)".
This leaves some unanswered questions as well: how will Cmd relay which method of class should be invoked? Keeping pointers wouldn't make sense and would be subject to high level of obscurity (as demonstrated above). Also, I wish to not reinterpret strings in onCmd method for every class that may handle that cmd.
It is a lot of information, but does anybody have any ideas on how to deal with this issue?
Also, all my classes must be aware of Commander and Console objects, which are no longer singleton/static. So far, I have placed them inside a Context object, and am passing it around like a little capsule. Any ideas on how to solve these post-singleton residual problems?
This project is my personal work, and I am planning to use it on my resume - hence, I do not want my potential employers to see any singletons (nor do I want to explain myself as to why, since I can prove to myself they are not truly necessary).
Thanks a ton!
edit: typography.

This is a job for the function class. You can find one in Boost, or in TR1 or C++0x. It looks like std::function<void()>, for example. This is often partnered with bind, which you will need if you want to refer to functional objects in a generic way, rather than take them by value, and is also found in Boost, TR1 or C++0x. If you have lambda functions, you can use them too, which is an excellent method.
class Commander {
std::map<std::string, std::function<void()>> commands;
public:
void RegisterCommand(std::string name, std::function<void()> cmd) {
commands[name] = cmd;
}
void CallCommand(std::string name) {
commands[name]();
}
};
void sampleFunc() {
std::cout << "sampleFunc()" << std::endl;
}
struct sampleStruct {
int i;
void operator()() {
std::cout << i;
std::cout << "sampleStruct()() and the value of i is " << i << std::endl;
}
};
int main() {
Commander c;
c.RegisterCommand("sampleFunc", sampleFunc);
sampleStruct instance;
instance.i = 5;
c.RegisterCommand("sampleStruct", instance);
std::string command;
while(std::cin >> command && command != "exit") {
c.CallCommand(command);
}
std::cin.get();
}

Related

Two versions of the program depending on the input parameter without code duplication

I am solving the following problem. I am working on an optimization program in C ++ which, depending on the initial settings of the user, uses various regulations (standards) to calculate the target function. Suppose we have a method A based on some norm and a method B based on another norm to calculate the target function. The user is setting the right standard before starting the program. The rest of the code is the same. During optimization, the target function is iteratively called over and over again. Of course, there is a simple solution: each time the target function is called, the IF condition is used to decide which standard to use. But because the program has to make decisions in every iteration, it seems to be ineffective. The second option is to create 2 independent codes and run only the one with the required standard. This, in turn, is ugly in terms of duplicate code.
I imagined that I would create 2 different classes and use the selected class using the IF condition when constructing the object. This would make the program decide only once when creating the object, but during the iteration itself the object would be clearly defined. Unfortunately, this does not work because objects cannot be created in IF conditions.
//-----------------------------------------------------------
// Create object sensor based on input
if(data.sensors_tipe == "Uniaxial_025") Sensor_Uniaxial_025 sensor(data);
else if (data.sensors_tipe == "T_rosette_05") Sensor_T_rosette_05 sensor(data);
else report.error("some error");
// rotation test
int element_index = 1;
double orientation_angle = 3.490658503988659;
sensor.rotate(element_index, orientation_angle);
Another way I would like is to set the correct method using a parameter in the constructor. Unfortunately, that probably isn't possible either.
I am a beginner and I did not find the answer anywhere. So maybe someone can help. Thanks
This is a good job for templates, which are "recipes" to generate code.
The end result will be duplicated machine code, but without the duplication in the source.
template<typename MethodT>
float optimize(const MethodT& method) {
float v = method();
// etc...
}
float methodA();
float methodB();
int main() {
auto a = optimize(methodA);
auto b = optimize(methodB);
}
First, the solution with if may be not that bad. It is branch on each function call, but the branch should be predicted well.
Second, if the functions that implement method A and method B are large enough to miss inlining, use function pointer.
Otherwise, use static polymorphism with templates, method A and method B may be passed via template parameter as functors.
In case, the user can change standard after programm compilation (for example, before each run) you can create interface and 2 child from it.
So, at startup you should create the instance (one of 2) you need through new. And then you can use it.
You can't use that algorithm with stack instances.
One way is to use inheritance.
class Sensor
{
public:
virtual void rotate(int, double) = 0;
};
class Sensor_Uniaxial_025 : public Sensor
{
public:
virtual void rotate(int, double) {/*stuff*/};
};
class Sensor_T_rosette_05 : public Sensor
{
public:
virtual void rotate(int, double) {/*stuff*/};
};
Sensor* sensorToUse;
//-----------------------------------------------------------
// Create object sensor based on input
if(data.sensors_tipe == "Uniaxial_025") sensorToUse = new Sensor_Uniaxial_025(data);
else if (data.sensors_tipe == "T_rosette_05") sensorToUse = new
Sensor_T_rosette_05(data);
else report.error("some error");
// rotation test
int element_index = 1;
double orientation_angle = 3.490658503988659;
sensorToUse->rotate(element_index, orientation_angle);
The example above, with new, comes with serious memory management issues. But if you pre-allocate the sensor for each type, in a single instance, and use a look-up instead it works well.
The alternative is with template. See other answers for these approaches.

dumb data object holds all common values c++, is this correct

So I am new to c++ and I'm writing for a scientific application.
Data needs to be read in from a few input text files.
At the moment I am storing these input variables in an object. (lets call it inputObj).
Is it right that I have to pass this "inputObj" around all my objects now. It seems like it has just become a complicated version of global variables. So I think I may be missing the point of OOP.
I have created a g++ compilable small example of my program:
#include<iostream>
class InputObj{
// this is the class that gets all the data
public:
void getInputs() {
a = 1;
b = 2;
};
int a;
int b;
};
class ExtraSolver{
//some of the work may be done in here
public:
void doSomething(InputObj* io) {
eA = io->a;
eB = io->b;
int something2 = eA+eB;
std::cout<<something2<<std::endl;
};
private:
int eA;
int eB;
};
class MainSolver{
// I have most things happening from here
public:
void start() {
//get inputs;
inputObj_ = new InputObj();
inputObj_ -> getInputs();
myA = inputObj_->a;
myB = inputObj_->b;
//do some solve:
int something = myA*myB;
//do some extrasolve
extraSolver_ = new ExtraSolver();
extraSolver_ -> doSomething(inputObj_);
};
private:
InputObj* inputObj_;
ExtraSolver* extraSolver_;
int myA;
int myB;
};
int main() {
MainSolver mainSolver;
mainSolver.start();
}
Summary of question: A lot of my objects need to use the same variables. Is my implementation the correct way of achieving this.
Don't use classes when functions will do fine.
Don't use dynamic allocation using new when automatic storage will work fine.
Here's how you could write it:
#include<iostream>
struct inputs {
int a;
int b;
};
inputs getInputs() {
return { 1, 2 };
}
void doSomething(inputs i) {
int something2 = i.a + i.b;
std::cout << something2 << std::endl;
}
int main() {
//get inputs;
inputs my_inputs = getInputs();
//do some solve:
int something = my_inputs.a * my_inputs.b;
//do some extrasolve
doSomething(my_inputs);
}
I'll recommend reading a good book: The Definitive C++ Book Guide and List
my answer would be based off your comment
"Yea I still haven't got the feel for passing objects around to each other, when it is essentially global variables im looking for "
so this 'feel for passing object' will come with practice ^^, but i think it's important to remember some of the reasons why we have OO,
the goal (in it simplified version) is to modularise your code so as increase the reuse segment of code.
you can create several InputObj without redefining or reassignig them each time
another goal is data hiding by encapsulation,
sometimes we don't want a variable to get changed by another function, and we don't want to expose those variable globally to protect their internal state.
for instance, if a and b in your InputObj where global variable declared and initialized at the beginning of your code, can you be certain that there value doesn't get changed at any given time unless you want to ? for simple program yes.. but as your program scale so does the chances of your variable to get inadvertently changed (hence some random unexpected behavior)
also there if you want the initial state of a and b to be preserved , you will have to do it yourself ( more temp global variables? )
you get more control over the flow of your code by adding level abstractions with classes/inheritances/operation overriding/polymorphisms/Abtract and interface and a bunch of other concepts that makes our life easier to build complex architectures.
now while many consider global variable to be evil, i think they are good and useful when used properly... otherwise is the best way to shoot yourself in the foot.
I hope this helped a bit to clear out that uneasy feeling for passing out objects :)
Is using your approach good or not strongly depends on situation.
If you need some high speed calculation you can't provide incapsulation methods for your InputObj class, though they are recommended, because it will strongly reduce speed of calculation.
However there are two rules that your can follow to reduce bugs:
1) Carefully using 'const' keyword every time you really don't want your object to modify:
void doSomething(InputObj * io) -> void doSomething(const InputObj * io)
2) Moving every action related with initial state of the object(in your case, as far as I can guess, your InputObj is loaded from file and thus without this file loading is useless) to constructor:
Instead of:
InputObj() { }
void getInputs(String filename) {
//reading a,b from file
};
use:
InputObj(String filename) {
//reading a,b from file
};
You are right that this way you have implemented global variables, but I would call your approach structured, and not complicated, as you encapsulate your global values in an object. This will make your program more maintainable, as global values are not spread all over the place.
You can make this even nicer by implementing the global object as a singleton (http://en.wikipedia.org/wiki/Singleton_pattern) thus ensuring there is only one global object.
Further, access the object through a static member or function. That way you don't need to pass it around as a variable, but any part of your program can easily access it.
You should be aware that a global object like this will e.g. not work well in a multithreaded application, but I understand that this not the case.
You should also be aware that there is a lot of discussions if you should use a singleton for this kind of stuff or not. Search SO or the net for "C++ singleton vs. global static object"

Hash table of "classes" (not objects) in C++

I need to make, for my college homework, an interpreter in C++ for a language based on functions (or commands). The interpreter has got to read an input file, extract the words (strings), generate the commands and execute them. All commands are classes which inherit from a common super-class (Command, for example), which's got a virtual method called execute. For each word read from the input file, a command is created and stored in a vector<Command>.
So, I'm thinking of using a hashtable, whose keys are the names of the commands (strings) and whose values are some kind of objects which allow me to create an specific class (or give me access to the constructor of an specific class), to easily create the classes for each word instead of using a chain of if-else-if's.
By now, I'm planning to create a CommandGenerator class with a virtual method called generate which returns a new Command object. The values of my commands hash table will be objects of theCommandGenerator class. So I derive from it many other subclasses for all commands, which return specific new objects derived from Command.
But, does anything like that already exist? Or is there any more elegant way to do that? Is there any kind of object that can be extracted from a class to represent it?
If each command is a subclass of Command, why don't you use a std::vector<Command*> and push pointers to instances of each subclass? Then you can iterate over the vector and call your virtual execute function.
The closest thing you can get about placing classes in a vector is boost::fusion::vector. But can't be filled at runtime, no use on your specific case.
Assuming you can use C++11. If you can define commands as just a execute function, you can do something like:
map<string, function<void()>> cmds = {
make_pair("print1", [](){
cout << "1" << end;
}),
make_pair("print2", [](){
cout << "2" << end;
}),
make_pair("print3", [](){
cout << "3" << end;
})
};
And then put the command on a vector with:
vector<function<void()>> list;
list.push_back(cmds["print1"]);
list.push_back(cmds["print1"]);
list.push_back(cmds["print2"]);
Then just execute with a loop:
for (function<void()>& cmd : list)
cmd();
This should print 112 to screen. But if you care a lot with speed, do a lot of ifs instead.
The basic problem you have is: You have the name of the class as a string and want to create a class with that name. This translation you have to do somehow manually, like you mentioned. This has been discussed here several times, like in Instantiating classes by name with factory pattern or in Looking for a better C++ class factory. The only addition I would make here: use good old macros, because they have a stringize-operator. E.g.:
#include <stdio.h>
#define CREATEOBJ(clss,command) if (strcmp (#clss, command)==0) return new clss;
class Base {
public:
virtual const char *name()=0;
};
class A : public Base {
public:
const char *name() {return "I am an A";}
};
class B : public Base {
public:
const char *name() {return "I am an B";}
};
Base *makeInstance (const char *nm) {
CREATEOBJ(A,nm);
CREATEOBJ(B,nm);
}
int main () {
printf ("%s\n", makeInstance ("A")->name());
printf ("%s\n", makeInstance ("B")->name());
}
of course you can make it nicer by using a hash-table containing the strings and some function-pointer or generator-class pointer, but the idea remains the same: to add a new class, just add one more CREATEOBJ-thingy.

How do you clone() in linux inside a class and namespace?

I'm taking an intro to operating systems course and we're to use the clone() call in linux to create threads and then do some stuff with them. I seem to be having trouble just using clone() at all.
I've structured my code into a single class (called Homework) which is in the namespace for the class (Course). This may be the problem as this is the first time I've really used the namespace keyword. I'm trying to use the things I rarely do to become more experienced with it so if I have a dumb mistake, so be it.
I found some articles on the web but they didn't help much. I've read the man page but I guess I'm not experienced enough to understand what the problem is. One day! Thanks for any assistance :)
I want to have the method to catch the clones inside the class:
// -- Header -- //
namespace _Course_ {
class _Homework_ {
...
int threadCatch(void *);
...
};
}
// -- Source -- //
namespace _Course_ {
void _Homework_::threadTest(void) {
...
// From web article
void **childStack;
childStack = ( void **) malloc(KILOBYTE);
clone(threadCatch, childStack, CLONE_VM | CLONE_FILES, NULL);
...
}
int _Homework_::threadCatch(void * ){
cout << getpid() << " cloned." << endl;
exit(0);
}
}
Is what I currently have. I've tried different ways (taking the catcher out of the class, then namespace). It's compiled twice but when I try to recompiled after a make clean it tells me the function (threadCreate) is declared in multiple locations. Because of these weird errors I'm sure I'm doing something wrong and instead of hack at it I'll take some opinions. What should I do, or what should I read next? Thanks!
Define your catch function as a static class function.
static int threadCatch(void *);
Also (and you probably don't need this, but just in case, I'll say it here) you might also need to use the scope resolution operators to send it to clone(). I don't think so, since you're using it inside of the Homework class already. but I say it just in case, it might help you.
clone(Homework::threadCatch, childStack, CLONE_VM | CLONE_FILES, NULL);
The clone(2) system call expects a pointer to a function with C linkage. Since you're using C++ I'd recommend moving your threadCatch() function into the global namespace and declare it as an extern "C" function. You could also declare the method in your class as static but I feel that making it a free function with C linkage more closely matches how the function is to be passed as a parameter.
If you need to make calls to C++ objects inside your threadCatch() function that exist outside of it's scope you can pass pointers to those objects as the arg parameter to the clone() call. Your threadCatch() function would then cast the arg to the appropriate type so that you can access your C++ object(s) accordingly.

How a member func can know *programmatically* the 'name of the object' that is calling it?

Let say we have a class MyClass that has and a memberfunc().
An object is created for this MyClass, say ObjA.
i.e MyClass ObjA;
ObjA calls memberfunc().
Can we get this name 'ObjA' inside memberfunc() programatically?
Note: I know how to get the type of the object, i.e 'MyClass', using RTTI (Run-Time Type Identification), the same is also explained by radman below.
EDIT:
If this is NOT POSSIBLE in c++, Is it possible in any other programming language?
EDIT2
Made some modification to the question as few were unable to interpret.
There are several issues here:
Objects don't call anything, code does.
Objects don't have a name. An object is usually assigned to a variable, often to more than one variable, often to no variable at all, such as an array element.
Getting access to the call stack might give you some idea of the calling class that owns the code that called you, but even this usually requires a level of introspection that goes beyond the reflection facilities of most languages.
Python is a notable exception. It can give you the stack to walk and figure out lots of interesting things. C++ won't.
I have seen C++ libraries that crack open the stack (this is very non-portable, by the way) and thus give code the ability to figure stuff out like, "Who called me?" but I haven't used that stuff for years.
No, there is no way for it. C++ has no reflection, which would might make this possible. On 2nd thought, even the reflection facilities of e.g. Java don't have this feature.
C++ is compiled directly to machine code, which does not contain any identifiers from the source code anymore. You could of course store the "variable name" in a member field (provided the object is referred to under a single name...).
No, the object name is something that only exists in your source code. Once compiled, the object reference is just a memory offset. If you want to know the variable name, you have to have a string somewhere describing it.
The facility to get a variable name in languages with introspection mechanisms (such as Reflection) is pretty limited and not at all widely available. Even in C# - the girly man language - to get a variable name you need to use a quirky C# 3.5 feature called projection and then jump through hoops to extract it. Even then, you have to program for it - it won't just be available at any point of the code.
After some thinking the question you are posing - getting the objects' name from a member function - is theoretically impossible. Consider this scenario:
class ObjA {
public:
void memberfunc() {
//confused??? instance1 or instance2?
}
};
//main
ObjA instance1;
ObjA* instance2 = &instance1;
instance2->memberfunc();
In the above example we have one instance of ObjA with two variables pointing to it(and I use term pointing rather loosely here). Those variables are something completely outside of any conceivable control of the object, hence it's impossible to get at them, even if the facility to get a variable name is available.
In C# you can use anonymous classes and Reflection to get a variable name. The method of doing so is quite awkward and if you are trying to use this to demonstrate something to someone, give up now, because you will both be confused. The technique uses some features that are new to mainstream programming and include anonymous classes, projection, extension methods and Reflection.
public static class Extensions {
public static string GetFirstPropertyName(this object obj) {
return obj.GetType().GetProperties()[0].Name;
}
}
public class Program {
public static void Main() {
int intVal = 5;
var name = (new {intVal}).GetFirstPropertyName();
//name=="intVal"
}
}
Well your question seems a little bit unclear but assuming that you want to print out the name of the class in one of it's member functions it is quite possible.
What you need to use is the typeid command. This extracts a close to human readable name for a an object of class type at runtime. However you can't rely on this name being consistent across platforms i.e. the name you get may vary from platform to platform (what I got from the example code below was '4ObjA'.
#include <iostream>
#include <typeinfo>
class ObjA
{
public:
void memberfunc()
{
std::cout << typeid(*this).name() << std::endl;
}
};
int main(int argc, char **argv)
{
ObjA obj;
obj.memberfunc();
}
Your question isn't entirely clear - do you want to know the object the method belongs to? Or the name of the method calling the member-function? Oo something else..?
In most object-oriented languages, you can get the name of the currently class quite easily:
class Myclass(object):
def memberfunc(self):
print self.__class__.__name__
obja = Myclass()
obja.memberfunc() # prints Myclass
You can't sensibly get the obja identifier as a name (in almost any language), and I can't see why you would want to (in cases like this, you'd use some kind of key/value mapping)
If you want to get the name of the method that called the method, you would have to inspect the call stack, e.g in Python using the inspect method:
import inspect
class Myclass(object):
def memberfunc(self):
current_call = inspect.stack()[0]
previous = inspect.stack()[1]
print previous[3]
def somefunc():
obja = Myclass()
obja.memberfunc() # prints somefunc
somefunc()
I imagine this isn't as easy in other languages
Again, the cases where you would want to do such a thing are rare, usually limited to introspection-heavy things like code coverage tools and debuggers
As has been covered in other posts, there is no direct way to access the variable name identifier that you choose in code at runtime - there is simply no need for it from the machine perspective. However, in Ruby it is trivial to get at the details of the caller in terms of its structure:
class Foo
def foo
puts self.class
end
end
class Bar < Foo
end
f = Foo.new
b = Bar.new
f.foo #=> Foo
b.foo #=> Bar
You can do similar in C++ with typeid, but it is not exact. For instance:
#include <iostream>
class Foo {
public:
void foo () { std::cout << typeid(this).name() << std::endl; }
};
int main () {
Foo f;
f.foo (); // on my system returns P3Foo
return 0;
}
This is sort of a hack, but you could use Macros to store the class identifier name. Here's what I mean:
#include <iostream>
#include <string>
#define createMyClass(x) MyClass x("x")
class MyClass{
string _name;
MyClass( const string& name ) : _name(name){}
memberfunc(){
std::cout << "Name: " << _name << std::endl;
}
}
int main (int argc, char **argv) {
createMyClass( ObjA );
ObjA.memberfunc(); // prints the name
return 0;
}