Casting inherited template class to parent class - c++

edit: Added the cast-problem.
I have a small C++ problem and hope you can help me with it.
I'm using a library that provides a class GenericHandler. I have to inherit from that class, override stuff and then register my handler with the library to get the magic running. As I need multiple handlers that overlap in some areas, I tried to use templates as follows
template <typename T>
class MyGenericHandler : public GenericHandler
{
// everything used for all handlers goes here
};
class MyIntHandler : public MyGenericHandler<int>
{
};
class MyFloatHandler : public MyGenericHandler<float>
{
};
// in main
std::shared_ptr<MyIntHandler> handler = std::make_shared<MyIntHandler>();
library::HandlerQueue.register(handler);
// error-message: "no viable conversion from shared_ptr<MyIntHandler> to shared_ptr<GenericHandler>.
// Same error if I try it like this:
std::shared_ptr<GenericHandler> handler = std::make_shared<MyIntHandler>();
However, I now can't cast MyIntHandler into the library provided GenericHandler anymore.
It did work before, when I had MyIntHandler : public GenericHandler, so I guess the template somehow broke stuff.
Is there a way to still get it working? Do I need to cast manually, if yes how would I best do that?

Got it fixed by using std::dynamic_pointer_cast it seems; still unsure why #prehistoricpenguin couldn't reproduce it though.

Related

How can I connect two classes (which don't know eachother) through public interface (C++)

I'm currently working on a project where everything is horribly mixed with everything. Every file include some others etc..
I want to focus a separating part of this spaghetti code into a library which has to be completely independent from the rest of the code.
The current problem is that some functions FunctionInternal of my library use some functions FunctionExternal declared somewhere else, hence my library is including some other files contained in the project, which is not conform with the requirement "independent from the rest of the code".
It goes without saying that I can't move FunctionExternal in my library.
My first idea to tackle this problem was to implement a public interface such as described bellow :
But I can't get it to work. Is my global pattern a way I could implement it or is there another way, if possible, to interface two functions without including one file in another causing an unwanted dependency.
How could I abstract my ExternalClass so my library would still be independent of the rest of my code ?
Edit 1:
External.h
#include "lib/InterfaceInternal.h"
class External : public InterfaceInternal {
private:
void ExternalFunction() {};
public:
virtual void InterfaceInternal_foo() override {
ExternalFunction();
};
};
Internal.h
#pragma once
#include "InterfaceInternal.h"
class Internal {
// how can i received there the InterfaceInternal_foo overrided in External.h ?
};
InterfaceInternal.h
#pragma once
class InterfaceInternal {
public:
virtual void InterfaceInternal_foo() = 0;
};
You can do like you suggested, override the internal interface in your external code. Then
// how can i received there the InterfaceInternal_foo overrided in External.h ?
just pass a pointer/reference to your class External that extends class InterfaceInternal. Of course your class Internal needs to have methods that accept InterfaceInternal*.
Or you can just pass the function to your internal interface as an argument. Something around:
class InterfaceInternal {
public:
void InterfaceInternal_foo(std::function<void()> f);
};
or more generic:
class InterfaceInternal {
public:
template <typename F> // + maybe some SFINAE magic, or C++20 concept to make sure it's actually callable
void InterfaceInternal_foo(F f);
};

Can use MFC template base class with DECLARE_DYNAMIC()?

I have several views in my app, that are almost the same, so I decided to create a CBaseView class and to not copy the code. So I have something like this:
template <class BASE_T, class BASE_DOC, class BASE_DLG>
class CBaseView : public CListView
{
DECLARE_DYNCREATE(CBaseView<BASE_T, BASE_DOC, BASE_DLG>)
void func1()
{
// GetData() is just another method in CBaseView
BASE_T oData = GetData();
...
}
void func2()
{
BASE_DOC* pDocument = (BASE_DOC*) CView::GetDocumet();
pDocument->DoSomething();
...
}
void func3()
{
...
BASE_DLG oBaseDlg();
oBaseDlg.DoModal();
...
}
}
IMPLEMENT_DYNCREATE(CBaseView<BASE_T, BASE_DOC, BASE_DLG>, CListView)
After that I want to use the CBaseView for the others views:
CMyView : public CBaseView <MyType, MyDocument, MyDlg> {...};
The problem is coming with:
DECLARE_DYNCREATE(CBaseView<BASE_T, BASE_DOC, BASE_DLG>)
and
IMPLEMENT_DYNCREATE(CBaseView<BASE_T, BASE_DOC, BASE_DLG>, CListView)
It gаve me some strange errors. I saw that I can't use this macros with a template class. Also found a similar topic, but I'm quite new in MFC (and in programming like all) and I can't rewrite it so to works for my three template arguments.
I'm worried that I tried everything I could think of and still haven't done it. I really need to find a way to do it or at least an alternative, so guys please help me!
I don't know MFC, but the problem is quite clear: The macros do not accept template instantiations. This is understandable, because macros are expanded first and once you instantiate the template, you wont have CBaseView<BASE_T, BASE_DOC, BASE_DLG> but something like CBaseView<Foo,FooDoc,FooDlG>, ie concrete types for the parameter.
DECLARE_DYNCREATE is to enable creation of instances on the fly at runtime, while templates only exist at compiletime, so at some point you'll need to decide what instantiations of the template you want to use at runtime. You could keep the implementation in the template, but for the types used with the framework you use:
class View1 : public CBaseView<Foo1,FooDoc1,FooDlg1> {
DECLARE_DYNCREATE(View1)
};
IMPLEMENT_DYNCREATE(View1,CListView)
class View2 : public CBaseView<Foo2,FooDoc2,FooDlg2> {
DECLARE_DYNCREATE(View2)
};
IMPLEMENT_DYNCREATE(View2,CListView)

Minimizing the amount of header files needed using the Builder/Fluent pattern

I am experimenting with the Builder/Fluent style of creating objects trying to extend some ideas presented in a course. One element I immediately didn't like with my test implementation was the large number of additional header files the client needs to include for the process to work, particularly when I wish to make use of public/private headers via the pImpl idiom for purposes of providing a library interface. I'm not entirely certain whether the problem lies with my implementation or I'm just missing an obvious 'last step' to achieve what I want.
The general gist is as follows (using the toy example of Pilots):
Firstly the client code itself:
(Note: for brevity, various boilerplate and irrelevant code has been omitted)
Pilot p = Pilot::create()
.works().atAirline("Sun Air").withRank("Captain")
.lives().atAddress("123 Street").inCity("London")
What's happening here is:
In Pilot.h, the Pilot class is defined with a static member method called create() that returns an instance of a PilotBuilder class defined in PilotBuilder.h and forward declared in Pilot.h
Essentially the PilotBuilder class is a convenience builder only used to present builders of the two different facets of a Pilot (.works() and .lives()), letting you switch from one builder to another.
Pilot.h:
class PilotBuilder;
class Pilot {
private:
// Professional
string airline_name_, rank_;
// Personal
string street_address_, city_;
Pilot(){}
public:
Pilot(Pilot&& other) noexcept;
static PilotBuilder create();
friend class PilotBuilder;
friend class PilotProfessionalBuilder;
friend class PilotPersonalBuilder;
};
Pilot.cpp:
#include "PilotBuilder.h"
PilotBuilder Pilot::create() {
return PilotBuilder();
}
// Other definitions etc
PilotBuilder.h
#include "public/includes/path/Pilot.h"
class PilotProfessionalBuilder;
class PilotPersonalBuilder;
class PilotBuilder {
private:
Pilot p;
protected:
Pilot& pilot_;
explicit PilotBuilder(Pilot& pilot) : pilot_{pilot} {};
public:
PilotBuilder() : pilot_{p} {}
operator Pilot() {
return std::move(pilot_);
}
PilotProfessionalBuilder works();
PilotPersonalBuilder lives();
};
PilotBuilder.cpp
#include "PilotBuilder.h"
#include "PilotProfessionalBuilder.h"
#include "PilotPersonalBuilder.h"
PilotPersonalBuilder PilotBuilder::lives() {
return PilotPersonalBuilder{pilot_};
}
PilotProfessionalBuilder PilotBuilder::works() {
return PilotProfessionalBuilder{pilot_};
}
As you can imagine the PilotProfessionalBuilder class and the PilotPersonalBuilder class simply implement the methods relevant to that particular facet eg(.atAirline()) in the fluent style using the reference provided by the PilotBuilder class, and their implementation isn't relevant to my query.
Avoiding the slightly contentious issue of providing references to private members, my dilemma is that to make use of my pattern as it stands, the client has to look like this:
#include "public/includes/path/Pilot.h"
#include "private/includes/path/PilotBuilder.h"
#include "private/includes/path/PilotProfessionalBuilder.h"
#include "private/includes/path/PilotPersonalBuilder.h"
int main() {
Pilot p = Pilot::create()
.works().atAirline("Sun Air").withRank("Captain")
.lives().atAddress("123 Street").inCity("London");
}
What I cannot figure out is:
How do I reorder or reimplement the code so that I can simply use #include "public/includes/path/Pilot.h" in the client, imagining say, that I'm linking against a Pilots library where the rest of the implementation resides and still keep the same behaviour?
Provided someone can enlighten me on point 1., is there any way it would be then possible to move the private members of Pilot into a unique_ptr<Impl> pImpl and still keep hold of the static create() method? - because the following is obviously not allowed:
:
PilotBuilder Pilot::create() {
pImpl = make_unique(Impl); /* struct containing private members */
return PilotBuilder();
}
Finally, I am by no means an expert at any of this so if any of my terminology is incorrect or coding practices really need fixing I will gladly receive any advice people have to give. Thank you!

Does cocos2d-x force multiple inheritance?

I have a class,
class Ticket : public cocos2d::CCNode, public cocos2d::CCTargetedTouchDelegate { ... };
Which works fine when I register for touch events on that node using:
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(ticket_, 0, true);
However, if I alter my class so that it uses composition rather than inheritance for the CCNode bit:
class Ticket : public cocos2d::CCTargetedTouchDelegate {
private:
cocos2d::CCNode* node_;
public:
Ticket() { node_ = new CCNode(); node_->init(); }
cocos2d::CCNode* node() { return node_; }
...
};
Then the following blows up with a SIGSEGV 11:
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(ticket_, 0, true);
I have added ticket_->node() to the current layer, but I am wondering if the touch dispatcher somehow doesn't like the node and the delegate to be different things. Or to put it another way, is touch dispatcher is expecting the node and the delegate to be the same thing?
So in short, my code works when I use multiple inheritance, but it doesn't when I use composition. Without delving into the framework, can anyone say that this is true, or have I just missed something obvious? I am using cocos2d-2.1rc0-x-2.1.2
Yes, it seems cocos2d-x indeed does force multiple inheritance. It expects the touch delegate to be dynamically castable to a CCObject, which your Ticket class isn't when you use composition. When you inherit from CCNode, which itself inherits from CCObject, you're in the clear. You can see the problem here on github.
This does not seem to be a mistake though, since the documentation actually hints at this by noting
IMPORTANT: The delegate will be retained.
for CCTouchDispatcher::addTargetedDelegate.

Boost python export singleton

I have a singleton (from boost::serialization):
class LogManager : public boost::serialization::singleton<LogManager> { ... };
And wrapper for getting instance:
inline LogManager &logManager() { return LogManager::get_mutable_instance(); }
What's the right way to bind this into boost.python module?
I tried:
class_< LogManager, boost::serialization::singleton<LogManager> >("LogManager", no_init)
...
;
As a result - a lot of ugly error text in console. What's wrong?
In addition to using bases<...> in the second argument as Autopulated pointed out, I think you also want to specifiy boost::noncopyable as the third template argument, e.g.
bp::class_<LogManager, bp::bases<boost::serialization::singleton<LogManager> >, boost::noncopyable>("LogManager", bp::no_init)
Edit:
Also, you need have a class declaration for any base classes listed, e.g.
bp::class_<boost::serialization::singleton<LogManager>, boost::noncopyable>("Singleton", bp::no_init)
Or, if you don't need access to the base class and won't be exporting any other children of boost::serialization::singleton<LogManager>, then you can omit specifying the base classes in the first place. That is, the following declaration is just fine if all you want to do is expose the LogManager class:
bp::class_<LogManager, boost::noncopyable>("LogManager", bp::no_init)
You want bp::bases< boost::serialization::singleton<LogManager> > as the second template parameter instead.