How to store get a correct Glib::RefPtr to a non-widget using Gtk::Builder - c++

It is rather simple to get a Glib::RefPtr to any widget by using get_widget function of Gtk::Builder, but when it comes to getting other objects the corresponding get_object function returns Glib::Object, which is not easily convertable to the needed class (such as Gtk::TreeView).
What is the appropriate way of doing that?

It would be best to use Glib::RefPtr<TheDerivedype>::cast_dynamic(object) .
However, Gtk::TreeView (which you mention in your question) is a Gtk::Widget, so you would use get_widget() instead of get_object().
If you meant, Gtk::TreeModel, well, defining GtkTreeModels in Glade, for use in gtkmm C++ code, is something that might work since we added some fixes for that in gtkmm recently:
https://bugzilla.gnome.org/show_bug.cgi?id=742637
But it's not something that we generally expect to work - many C++ developers would prefer the static type safety of defining the DataModel structure completely in code, and not relying on a translation between C and C++ types. For instance: https://developer.gnome.org/gtkmm-tutorial/stable/sec-treeview-model.html.en#treeview-model-liststore

Glib::RefPtr has a static template function which allows one to do what is needed. This function is logically called cast_static.
The sample code can be:
treeStore =
Glib::RefPtr< Gtk::TreeStore >::cast_static( builder->get_object("treestore1") );

Related

Delegates in C++

I am going through a code and I have come across the following code snippets
using ConnectCallback = delegate<void(Connection_ptr self)>;
using DisconnectCallback = delegate<void(Connection_ptr self, Disconnect)>;
I have tried to understand about delegates, but the sources were of no help.
What is the function of delegate in the above code ?
C++ has no out-of-the-box delegate keyword, so with language confusion eliminated the only thing left is delegate being a template defined elsewhere.
delegate doesn't do anything in the given snippet. It is merely an identifier that is being aliased. The action will occur later when the alias is used. Without the definition of delegate any number of things could be going on behind the scenes inside the delegate template, but this code snippet is defining a pair of aliases to the delegate template with specific prototypes of function pointers.
Instead of having to type delegate<void(Connection_ptr self)> or delegate<void(Connection_ptr self, Disconnect)>, the programmer can use ConnectCallback or DisconnectCallback which is probably cleaner and has more meaning in context. We don't have context here, unfortunately, so I can't give a good example of usage.

How to cast const FB::variant& into user defined class in c++?

I am tryintg to cast const FB::variant& sample into SampleJS* in C++.
like this:
SampleJS* info = sample.cast<SampleJS*>();
i do not know what is going wrong here.
this gives me error of:
boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_any_cast> >
Thank you in advance.
You need to understand that FB::variant just stores whatever type is put into it. Your code will absolutely work... if what is inside happens to be a MouseInfoJS*. However, you'd have to go through a lot of work to put something like that inside, since the FB::variant class is designed to make it difficult, but not impossible, to store inside it types that it doesn't know.
So basically, what you're trying to do probably doesn't make any sense, so you can't do it.
Depending on what type MouseInfoJS is, it might sorta make sense. Does MouseInfoJS inherit from JSAPI? (or JSAPIAuto?) If so, then it would somewhat make sense to try what you're doing, except that you'd never have a MouseInfoJS*, you'd have a MouseInfoJSPtr, which would be a typedef for boost::shared_ptr, since it would then be partially owned by the page and thus dangerous to store a raw pointer there.
Even in this case, which you'd need to use .convert_cast<MouseInfoJSPtr>, not .cast, it won't work on most modern browsers because they wrap the NPObject returned by FireBreath in another object which doesn't allow us to get the original object back; I believe this is a security feature. For more information, see A firebreath JSAPI will not be recognized in firefox

Passing pointer-to-member-function as pointer-to-function

So here's the situation: I'm using C++, SDL and GLConsole in conjunction. I have a class, SDLGame, which has the Init(), Loop(), Render() etc - essentially, it holds the logic for my game class.
GLConsole is a nice library so far - it lets me define CVars and such, even inside my SDL class. However, when defining commands, I have to specify a ConsoleFunc, which is typedef'd as
typedef bool (*ConsoleFunc)( std::vector<std::string> *args);
Simple enough. However, like I said, my functions are all in my class, and I know I can't pass pointer-to-class-functions as pointer-to-function arguments. I can't define static functions or make functions outside my class because some of these ConsoleFuncs must access class data members to be useful. I'd like to keep it OOP, since - well, OOP is nice.
Well, I actually have this problem "solved" - but it's extremely ugly. I just have an instance of SDLGame declared as an extern variable, and use that in my ConsoleFuncs/main class.
So, the question is: Is there a way to do this that isn't stupid and dumb like the way I am doing it? (Alternatively: is there a console library like GLConsole that supports SDL and can do what I'm describing?)
If the only interface you have is that function pointer, then you're screwed.
A member function needs a this pointer to be called, and if you have no way of passing that, you're out of luck (I guess the std::vector<std::string>* args pointer is what you get passed from the library).
In other words, even though that library uses C++ containers, it's not a good C++ library, because it relies on free functions for callbacks. A good C++ library would use boost::function or something similar, or would at the very least let you pass a void* user_data pointer that gets passed through to your callback. If you had that, you could pass the this pointer of your class, cast it back inside the callback, and call the appropriate member function.

What is meant by delegates in C++?

What is mean by delegates in c++, does sort function in c/c++ which takes a compare function/functor as last parameter is a form of delegate?
"delegate" is not really a part of the C++ terminology. In C# it's something like a glorified function pointer which can store the address of an object as well to invoke member functions. You can certainly write something like this in C++ as a small library feature. Or even more generic: Combine boost::bind<> with boost::function<>.
In C++ we use the term "function object". A function object is anything (including function pointers) that is "callable" via the function call operator().
std::sort takes a "predicate" which is a special function object that doesn't modify its arguments and returns a boolean value.
Callback functions in C++ can be (loosely) referred as a form of delegates ( though delegate term is not used for this). The callback functions use Pointers to Functions to pass them as parameters to other functions.
But delegates in C# is more advanced compared to callback functions in C++.
To delegate work means to share the work load with others. In real life, if you were to delegate your task, ie if you are a manager, you would be sharing your work expecting others to complete a task without you having to know how.
The concept is the same in C++ and any other languages having the capability of delegates. In C you could see this as a delegate:
int calculate(int (*func)(int c), int a, int b)
Because you are expected to send a pointer, to another function which will compute some work for you. I recently wrote a blog post on function pointers in Python and C, check it out, you might find it helpfull. This might not be the "traditional" way to delegate work in C or C++, but then again, the termonoligy says i am a bit right.
Delegation is mostly used as a way to pass functions to functionality embedded in a class (pimpl, aggregation, private inheritance). They are mainly (inlined) functions of one line, calling functions of member-classes. As far as I know, it has nothing to do with C#'s delegates.
In this sense, a function-pointer as used in qsort is not a delegate, but a callback in which framework modules can be extended by user-software as in the Hollywood principle.
Delegate: An object that acts like a multi-function pointer with a subscription system. It really simplifies the use of static or 'object' member function pointers for callback notifications and event handling.
This link explains Delegates in a lucid manner or you may also refer to the MSDN link.

Extending an existing class like a namespace (C++)?

I'm writing in second-person just because its easy, for you.
You are working with a game engine and really wish a particular engine class had a new method that does 'bla'. But you'd rather not spread your 'game' code into the 'engine' code.
So you could derive a new class from it with your one new method and put that code in your 'game' source directory, but maybe there's another option?
So this is probably completely illegal in the C++ language, but you thought at first, "perhaps I can add a new method to an existing class via my own header that includes the 'parent' header and some special syntax. This is possible when working with a namespace, for example..."
Assuming you can't declare methods of a class across multiple headers (and you are pretty darn sure you can't), what are the other options that support a clean divide between 'middleware/engine/library' and 'application', you wonder?
My only question to you is, "does your added functionality need to be a member function, or can it be a free function?" If what you want to do can be solved using the class's existing interface, then the only difference is the syntax, and you should use a free function (if you think that's "ugly", then... suck it up and move on, C++ wasn't designed for monkeypatching).
If you're trying to get at the internal guts of the class, it may be a sign that the original class is lacking in flexibility (it doesn't expose enough information for you to do what you want from the public interface). If that's the case, maybe the original class can be "completed", and you're back to putting a free function on top of it.
If absolutely none of that will work, and you just must have a member function (e.g. original class provided protected members you want to get at, and you don't have the freedom to modify the original interface)... only then resort to inheritance and member-function implementation.
For an in-depth discussion (and deconstruction of std::string'), check out this Guru of the Week "Monolith" class article.
Sounds like a 'acts upon' relationship, which would not fit in an inheritance (use sparingly!).
One option would be a composition utility class that acts upon a certain instance of the 'Engine' by being instantiated with a pointer to it.
Inheritance (as you pointed out), or
Use a function instead of a method, or
Alter the engine code itself, but isolate and manage the changes using a patch-manager like quilt or Mercurial/MQ
I don't see what's wrong with inheritance in this context though.
If the new method will be implemented using the existing public interface, then arguably it's more object oriented for it to be a separate function rather than a method. At least, Scott Meyers argues that it is.
Why? Because it gives better encapsulation. IIRC the argument goes that the class interface should define things that the object does. Helper-style functions are things that can be done with/to the object, not things that the object must do itself. So they don't belong in the class. If they are in the class, they can unnecessarily access private members and hence widen the hiding of that member and hence the number of lines of code that need to be touched if the private member changes in any way.
Of course if you want to access protected members then you must inherit. If your desired method requires per-instance state, but not access to protected members, then you can either inherit or composite according to taste - the former is usually more concise, but has certain disadvantages if the relationship isn't really "is a".
Sounds like you want Ruby mixins. Not sure there's anything close in C++. I think you have to do the inheritance.
Edit: You might be able to put a friend method in and use it like a mixin, but I think you'd start to break your encapsulation in a bad way.
You could do something COM-like, where the base class supports a QueryInterface() method which lets you ask for an interface that has that method on it. This is fairly trivial to implement in C++, you don't need COM per se.
You could also "pretend" to be a more dynamic language and have an array of callbacks as "methods" and gin up a way to call them using templates or macros and pushing 'this' onto the stack before the rest of the parameters. But it would be insane :)
Or Categories in Objective C.
There are conceptual approaches to extending class architectures (not single classes) in C++, but it's not a casual act, and requires planning ahead of time. Sorry.
Sounds like a classic inheritance problem to me. Except I would drop the code in an "Engine Enhancements" directory & include that concept in your architecture.