object.Object.Monitor being prefered over own Monitor class - d

I am in progress of writing a render system in D2, but it is really annoying me that D prefers its own monitor class object.Object.Monitor (Which I never imported by the way) over my own Monitor class.
What's a way to prevent D from using its monitor class instead of mine? I know I could append the conventional underscore, or simply use its full name (myapp.graphics.x11.Monitor) but this class will be used an awful lot, so these fixes aren't really ideal.
module app;
class Monitor {
public Monitor returnMe() {
return this; // Error: cannot implicitly convert expression (this) of type app.Monitor to object.Object.Monitor
}
}
void main() {
Monitor monitor = new Monitor;
monitor.returnMe();
}

I think this is because inside the class Monitor, your class name doesn't quite exist yet so the compiler thinks the already existing Monitor (it is in object.d which is auto imported) is a better match.
I actually think this should be considered a compiler bug, since if the other Monitor didn't exist, this code would indeed work. edit: Actually, since Monitor is a nested class in Object, this is /not/ a compiler bug, nested names always override outer names. So it is just weird that Object base class has a nested one called Monitor. /edit
But to work around the thing for now, you can use typeof(this) inside the Monitor class instead of its name. That will disambiguate inside, and the outside code still works correctly:
module app;
class Monitor {
// changed the name only inside the class
public typeof(this) returnMe() {
return this;
}
}
void main() {
// works normally here
Monitor monitor = new Monitor;
monitor.returnMe();
}

Related

A proper way to restrict access to an interface?

Let's say I have a class that represents a printing job: CPrintingJob. It knows nothing of the document being printed, just the job state - whether the job was queued, rejected, carried on etc.
The idea is an object of this class is instantiated whenever some printing needs to be done, then passed to the printing module along with other data, then the job's creator checks its state to see how printing is going.
Suppose CPrintingJob inherits two interfaces:
class IPrintingJob // this one is to check the job state
{
virtual TState GetState() const = 0;
// ... some other state-inquiring methods
class ICallback // job's owner is notified of state changes via this one
{
virtual void OnStateChange( const IPrintingJob& Job ) = 0;
};
};
and
class IPrintingJobControl // this one is for printing module to update the state
{
virtual void SetState( const TState& NewState ) = 0;
// ... some other state-changing methods
};
Problem is, the class that creates a CPrintingJob object shouldn't have access to the IPrintingJobControl, but the printing module CPrintingJob is being passed to must be able to change its state and, therefore, have access to that interface.
I suppose this is exactly the case where friends should be used but I have always avoided them as an inherently flawed mechanic and consequently have no idea of how to use them properly.
So, how do I do it properly?
Use a factory and have the factory return an instance of IPrintingJob (best wrapped inside a smart_ptr). e.g.:
struct PrintingFactory {
static auto create() -> std::unique_ptr<IPrintingJob> {
return std::unique_ptr<IPrintingJob>(new CPrintingJob());//as there is currently no std::make_unique..
}
}
Once you have to use the JobControl you can simply cast the pointer via std::dynamic_pointer_cast.
After some deliberation I've decided that:
This whole thing is definitely more trouble than it's worth;
(A slightly modified) version of MFH's answer above is the only, hence the best, way to go.
Thanks everyone for the input, it certainly has been enlightening.

C++/W32 Sharing Class - code design question

Here is what i am trying to do.
I have Three Classes:
1) CEngine
2) CLogManager
3) CWindowGL
Ad1.
This class 'does' the tricky things to get the game engine going,
an application utilizing it, can call only few public members to
get the game going -
class CEngine
{
public:
CEngine();
~CEngine(); // should this go to private?
bool Init(width,height,...);
void Destroy();
void Run();
bool LoadMap(...);
private:
CLogManager *m_pLogManager;
CWindowGL *m_pWindowManager
}
// Example usage
CEngine *Engine=new CEngine;
Engine->Initialize(...)
Engine->LoadMap(...)
Engine->Run()
Engine->Destroy()
delete(Engine)
Ad2.
This class controls the logging facility
it just allows me to dump some log into the log data file:
class CLogManager
{
public:
CLogManager();
~CLogManager();
void Write(const char *fmt,...);
private:
FILE *fp;
std::string m_sFileName; // unique filename generated at the constructor
SYSTEMTIME m_tSystemTime;
}
Ad3.
This class handles the window creation, and pixel format settings,
and few other things related to the window itself - nothing else,
but it also needs to utilize CLogManager - to dump few informations
for debug purposes.
Now the question is:
When a CLogManager constructor is called, class generates a unique filename that is:
m_sFileName="data/logs/enginelog_%i%i%i.txt"; // hour, minute, second
CEngine class in the Init method does:
m_pLogManager = new CLogManager;
and later on it uses it with m_pLogManager->Write(....) to log events.
That's ok for CEngine, but i would like to use the same functionality
in CWindowGL class and here is the question.
I would like my code to share CLogManager across :
CEngine
CWindowGL
...
...
...
and few others that i'll implement.
I can't do this by adding "Instance()" type of method like:
static CLogManager &Instance()
{
static CLogManager s_instance;
return s_instance;
}
and calling:
CLogManager::Instance().Write(" LOG MESSAGE ");
As this would cause my CLogManager to generate new filename each time when a
constructor is called.
Do i have to
extern CEngine *Engine;
somewhere to call
Engine->Log(" LOG MESSAGE ")
wrapper everytime or there is something else i can stick to?
I know it is more like a 'code-design' question, but i would like to see
how do you guys handle such things.
Normally i would do this with extern, but that would require me to check
m_pLogManager!=NULL within a wrapper function to a private member - and just
don't know if that's OK.
Maybe there's some other - better approach?
I will be adding few other classes like. TexturesManager - and would like this class to
store the actual size of textures loaded and so on, so this would also require me to
not to call Instance() to class each time the texture is called - as this would create/destruct the class without storing the needed size / array of textures already loaded...
Uff..
Thanks, hope this is clear.
I can't do this by adding "Instance()" type of method as this would cause my CLogManager to generate new filename each time when a constructor is called.
Actually no, the constructor would be called only once during your program lifetime. The singleton pattern is what you most likely want for your logging class.
What you'll generally find in these situations is a static set of methods that use a singleton underneath. All consumers call the static method which returns the one, single, instance of your logger, which you then call methods on.

Boost.Python: Grab 'self' from member function

Class member functions in Python have to explicitly declare a self parameter which represents the class instance. Is there a way to get a hold of self from C++, by using Boost?
class FooBar
{
public:
void func() {
}
};
// A wrapper for the above class
struct FooBar_W
: public FooBar
{
void func(boost::python::object self) {
// Do smth with `self`
FooBar::func();
}
};
BOOST_PYTHON_WRAPPER(module)
{
class_<FooBar_W>("FooBar")
.def("func", &FooBar_W::func)
;
}
Edit: Why I want self
I'm writing an event system for my game and I want the scripter to be able to define new types of events. I need a way to distinguish between different types of events. My Python code looks something like this:
class KeyboardEvent(Event):
pass
def onKeyPress(event):
pass
# EventManager is defined in C++
em = EventManager()
# This is how I register a new callback function with the manager
# The `onKeyPress` function will now only be notified when an event
# of type `KeyboardEvent` occurs. (Notice that I passed the actual
# class object, and not an instance of it.)
em.addEventHandler(KeyboardEvent, onKeyPress)
# This is how I queue new events
# (This time I pass an instance of an event, not a type of event.)
em.queueEvent(KeyboardEvent())
The manager needs to figure out what type of event I just queued. I figured I should do something like type(event).__name__ (but in C++, not in Python). This way I can determine the type and know which functions to notify of the event. I want to get self in C++ so I can access the __name__ attribute of its type.
I could have the scripter manually edit a new field that holds the name of the type, but why? That information already exists (the __name__ attribute) so why duplicate it, but more importantly, why bother the scripter with implementation details?
It's doable. The way to do it can be found in the link below; that page documents one way (the old way) to expose pure virtual functions. The example can be adapted to other needs, though.
> http://wiki.python.org/moin/boost.python/OverridableVirtualFunctions#Pure_Virtual_Functions
it's an old question, but for those who are still looking for a reasonably simple solution:
Static function (non-member as well as member) receive a const boost::python::object& self as the first argument. So you can do the following:
class FooBar
{
public:
static void func(const boost::python::object self) {
FooBar& thisref = boost::python::extract<FooBar&>(self)();
// use self as well as thisref
}
};
};
BOOST_PYTHON_WRAPPER(module)
{
class_<FooBar>("FooBar")
.def("func", &FooBar::func)
;
}
self in python is this in C++.
You can think of the line FooBar::func(); as translating to static_cast<FooBar*>(this)->func()

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;
}

dynamic_cast returns NULL but it shouldn't

I'm having the following class hierarchy:
class IStorage {
[...]
}
Q_DECLARE_INTERFACE(IStorage, "ch.gorrion.smssender.IStorage/1.0")
class ISQLiteStorage: public IStorage {
Q_INTERFACES(IStorage)
[...]
}
Q_DECLARE_INTERFACE(ISQLiteStorage, "ch.gorrion.smssender.ISQLiteStorage/1.0")
class DASQLiteStorage: public QObject, public ISQLiteStorage {
Q_OBJECT
Q_INTERFACES(ISQLiteStorage)
[...]
}
I'm using QT and am trying to create a plugin (for my app) with QtPlugin.
I'm creating an instance of DASQLiteStorage and I give this instance to an object FROM WITHIN the plugin:
// the next line is within my main app.
// storage is the DASQLiteStorage instance.
// gateway is an object from within the plugin.
gateway->setDefaultStorage(storage);
// this method lies within the plugin
void AbstractGateway::setDefaultStorage(IStorage* storage) {
defaultStorage_ = dynamic_cast<ISQLiteStorage*>(storage);
}
The problem is, that the dynamic_cast is returning me a null-pointer (not expected), while doing the dynamic_cast within my main app (i.e. before "gateway->setDefaultStorage(storage);") gives me the valid pointer (expected).
Does anyone know why this could happen? Is the program operating in a different memory range as the plugin? Could this lead to such problems? Any ideas how to fix this?
Thanks a lot!
EDIT:
I've tried out some suggestions:
// this method lies within the plugin
void AbstractGateway::setDefaultStorage(IStorage* storage) {
ISQLiteStorage* s = dynamic_cast<ISQLiteStorage*>(storage);
s = static_cast<ISQLiteStorage*>(storage);
s = qobject_cast<ISQLiteStorage*>((QObject*)storage);
defaultStorage_ = s;
}
In the first line of the method, s equals NULL, in the second s contains the correct pointer and in the third an other pointer. Why aren't these pointers equal?
And why could the dynamic_cast be still not working although I'm using now:
pluginLoader()->setLoadHints(QLibrary::ResolveAllSymbolsHint | QLibrary::ExportExternalSymbolsHint);
EDIT2:
I noticed, that the segmentation fault I get a little further in the code is also related to this. I have the following construct:
// The following classes are defined within the main app.
class ILoginAccount: public IAccount [...]
class AbstractAccountStroageOfficer {
public:
AbstractAccountStroageOfficer(IAccount* account)[...]
}
// These classes are defined within my plugin and are created from within the plugin.
class BCAccount: public ILoginAccount {
public:
BCAccount()
: ILoginAccount(new DAAccountStorageOfficer(this))
{};
}
class DAAccountStorageOfficer: public AbstractAccountStorageOfficer {
public:
DAAccountStorageOfficer(ILoginAccount* account)
: AbstractAccountStorageOfficer(account) // This line raises a segfault.
{
IAccount* a = account; // This line raises a segfault as well.
a = dynamic_cast<IAccount*>(account); // This as well.
a = static_cast<IAccount*>(account); // This as well.
}
}
These segmentation faults should not occur, should they? But why do they?
Basically, RTTI is unreliable across module boundaries. Different compilers have different behaviors here; you'll have to research how your compiler/version acts in this case. Of course, if you have a different compiler/version for the main app and plugin, it clearly has no chance of working.
Use static_cast as a work around.