Error while trying to use boost::factory - c++

I am trying to use boost factory and I am experiencing the following problem.
All I am trying to do is having a bunch of derived classes to have a mechanism that will be initializing the derived class that is matched with a corresponding string.
To begin with I have the following base class called name NetWorkBlock,
NetWorkBlock.h
class NetWorkBlock {
protected:
typedef boost::function<NetWorkBlock * ()> NetWorkFactory;
//definition of the function that will be used for the factory
public:
NetWorkBlock();
virtual ~NetWorkBlock();
//some basic functionalities that not related to the factory
and thus not mentioned
static std::map<std::string,NetWorkBlock::NetWorkFactory>& f_factory();
//static function that initializes and returns the map
};
NetWorkBlock.cpp
NetWorkBlock::NetWorkBlock() {
} //empty constructor
NetWorkBlock::~NetWorkBlock() {
} //empty deconstructor
std::map<std::string,NetWorkBlock::NetWorkFactory>& NetWorkBlock::f_factory()
{
static std::map<std::string,NetWorkBlock::NetWorkFactory>* ans =
new std::map<std::string,NetWorkBlock::NetWorkFactory>();
return *ans;
} //initialization of map
Moving on here is how I define things in the the derived class BusNetworkBlock (note ofcourse
there are more derived classes expected to be defined later, but in the current moment I work with a single derived class to manage to have things working):
BusNetworkBlock.h
class BusNetworkBlock {
public:
BusNetworkBlock();
virtual ~BusNetworkBlock();
//some basic functionalities that not related to the factory
and thus not mentioned
private:
/* Very small, "fake" class _initializer. Its only meaning is to define a
static member _init that is initialized at the very beginning of the
main(). Hence the constructor is called, and the constructor registers
the BusNetworkBlock class into the (static) NetWorkBlock::f_factory. */
static class _init {
public:
_init() {
NetWorkBlock::f_factory()["LoadCurve"] = boost::factory<BusNetworkBlock *>();
}
}_initializer;
};
BusNetworkBlock.cpp
BusNetworkBlock::BusNetworkBlock() {
} //empty constructor
BusNetworkBlock::~BusNetworkBlock() {
} //empty deconstructor
/* The definition of the bodies of the funcionalities of the class that are not mentioned here since they are not connected with the factory */
BusNetworkBlock::_init BusNetworkBlock::_initializer;
/* Ensure that the static member _initializer is initialized, so that
BusNetworkBlock is registered into NetWorkBlock::f_factory. */
Now in an other separate class under the name UCBlock I try to use the factory in order to initialize properly the derived NetworkBlock class based on a string I receive in the following way:
UCBlock.h
class UCBlock {
public:
UCBlock(std::istream& inStream); //the received instream
virtual ~UCBlock();
//some basic functionalities that not related to the factory
and thus not mentioned
NetWorkBlock * Network; /*defining a pointer of the base class NetWorkBlock
that want to initialize properly via the factory */
};
UCBlock.cpp
UCBlock::UCBlock( std::istream& inStream ) {
inStream >> network; //setting the string of network the corresponding factory
Network = NetWorkBlock::f_factory()[network](); // set the corresponding object via factory **here is where the problem arises**
}
And the problem arises when I try to use the factory to proper initialize the
derived class of NetWorkBlock. I receive the following error:
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_function_call> >'
what(): call to empty boost::function
Aborted (core dumped)
Now I have ofcoruse tried to check this thing online but didn't manage to come up with a solution and that's why I would really appreciate any kind of help here, since I am really stacked here. (Note also that I checked that the string I receive is correct and matches with "LoadCurve").

Related

Initializing a new nested class from outer class function

I'm currently learning nested classes in C++ while building a project and I currently inside setupBLE() I need to pass one of the nested classes but to init that new class I need to pass to its constructor the outer class so it can access its variables and functions but I'm not exactly sure how to pass to the constructor the pointer of the class that's trying to create it.
It's a bit confusing so I hope the code helps with it.
Like in python we have self but in C++ as far as I know we don't have that so I was wondering what should I pass to the constructor.
Code (PillDispenser.h):
class PillDispenser {
public:
explicit PillDispenser(BLEAddress deviceAddress);
private:
BLEAddress _device_address;
BLEAdvertisedDevice _device;
bool _connected;
// Device properties
std::string _device_name;
// Callbacks
static void notifyCallBack();
class AdvertisedDeviceCallBack : public BLEAdvertisedDeviceCallbacks {
PillDispenser &_outer;
explicit AdvertisedDeviceCallBack(PillDispenser &outer) : _outer(outer){};
void onResult(BLEAdvertisedDevice advertisedDevice) override;
};
}
Code (PillDispenser.cpp):
void PillDispenser::setupBLE() {
BLEScan *scanner = BLEDevice::getScan();
scanner->setAdvertisedDeviceCallbacks(new AdvertisedDeviceCallBack());
scanner->setInterval(SCAN_INTERVAL);
scanner->setWindow(SCAN_WINDOW);
scanner->setActiveScan(true);
scanner->start(SCAN_DURATION);
}
Issue:
This line is trying to use the default constructor which does not exist
scanner->setAdvertisedDeviceCallbacks(new AdvertisedDeviceCallBack());
instead you should use the explicit constructor you defined
scanner->setAdvertisedDeviceCallbacks(new AdvertisedDeviceCallBack(*this));
note that this (in this context) has type PillDispenser* so you have to dereference with * to get a PillDispenser&

How to access the function in base class when using singleton class as a derived class

It is a header of generator class;
#ifndef GENERATOR_H
#define GENERATOR_H
class Generator
{
public:
Generator(int);
~Generator();
int getBits();
private:
int bits;
};
#endif // GENERATOR_H
.
It is a header of proxy class which is singleton class drived from Generator;
#ifndef PROXY_H
#define PROXY_H
#include "Generator.h"
class Proxy: private Generator
{
public:
~Proxy();
static Proxy* getInstance(int);
Generator * operator ->();
int checkvalue();
private:
Proxy();
Proxy(int);
int bits;
int counter;
static Proxy* instance;
Generator * rPointer;
};
#endif // GENERATORPROXY_H
.
This is CPP file for Proxy.
Proxy::Proxy(int inputbits):Generator(inputbits)
{
}
Proxy::~Proxy()
{
}
Generator * Proxy::operator ->()
{
counter++;
if(counter<=10)
return rPointer;
else
return 0;
}
Proxy* Proxy::instance = 0;
Proxy* Proxy::getInstance(int inputbits)
{
if(instance==0)
{
instance = new Proxy(inputbits);
}
return instance;
}
Question: When I make some proxy object in main function, how I can call the getBits() function in main?
This is part of main function:
Proxy* px = Proxy::getInstance(4);
cout << px->getBits() << endl;
When I tried it error happend like this: int Generator::getBits() is inaccessible. Generator is not an accessible base of Proxy.
The way I can access Generator in main, I made operator like this: Generator * Proxy::operator ->() which is in CPP file for proxy. How can I access to the getBits() function in main function? Thank you all your help.
Issue 1:
The inheritance is private that means everything from the base Generator class is going into the private part of Proxy class.
If The public functions from Generator are to be visible, then You need make the inheritance public
-or-
create a public function in Proxy which calls the needed functions in Generator
Issue 2:
Inheritance is used when we need to use Derived classes (many times unknown classes) in a certain context. The Base class represents the abstract concept behind all the Derived classes. And it is used as a "common" concept between all the Derived classes.
In other words: Is the Generator an abstraction of a Proxy -or- is the Proxy a specific type of Generator.
If not, then I would use composition (make it a variable in Proxy).
Issue 3:
In the comments, there is also a requirement to the amount of times the Generator class is accessed. With inheritance, the Generator class has to control all the access to it.
So this is why You have a Proxy class. It is an extra level of indirection - it is a wrapper for Your Generator class, it should delegate all the calls to it.
The Proxy class should have all the required functions that need to be called. It is the "protector" of the Generator class (That's probably why private inheritance is used).
These issues are design issues, for which You have to decide, what is best.
To use Proxy::operator-> you have to dereference px first. So (*px)->getBits() should do the trick.
And as Eduard Rostomyan says, you should use a composite instead of inheritance, since a Proxy is not a Generator.
Additionally, you are not setting rPointer anywhere in your code sample and your code.

Best way to change from base class to derived class

I know this is asked in various ways on this forum, but I still can't quite figure out the best way to go about what I need to do (after reading various other posts). So I have decided to seek further advice!
I have a message class hierarchy, something like (omitted most details):
class MsgBase
{
public:
uint8_t getMsgType(void);
protected: // So that derived classes can access the member
char _theMsgData[100];
}
class MsgType1 : public MsgBase
{
}
class MsgType2 : public MsgBase
{
}
So what happens is I received a block of message data and I use it to create my message. But I don't know which message to create until I read out the message type. So I end up with:
MsgBase rxMsg(rxData);
if (rxMsg.getMsgType() == 1)
{
// Then make it a MsgType1 type message
}
else if (rxMsg.getMsgType() == 2)
{
// Then make it a MsgType2 type message
}
This is the bit I am stuck on. From what I have read, I cannot dynamical cast from base to derived. So my current option is to instantiate a whole new derived type (which seems inefficient), i.e.:
if (rxMsg.getMsgType() == 1)
{
// Now use the same data to make a MsgType1 message.
MsgType1 rxMsg(rxData);
}
Is there a way that I can look at the data as the base class so that I can determine its type and then "molymorph" it into the required derived type?
Thanks,
Fodder
What is rxData? I assume it's just a blob of data, and you should parse it to determine the message type before you create any message object. And depending on if the message data has always the same length you should consider using std::array or std::vector to pass the data blob around.
typedef std::vector<char> MsgDataBlob;
class MsgBase
{
public:
uint8_t getMsgType();
MsgBase(MsgDataBlob blob) : _theMsgData(std::move(blob)) {}
protected: // So that derived classes can access the member
MsgDataBlob _theMsgData;
};
//derived classes here...
//this could be either a free function or a static member function of MsgBase:
uint8_t getMessageType(MsgDataBlob const& blob) {
// read out the type from blob
}
std::unique_ptr<MsgBase> createMessage(MsgDataBlob blob) {
uint8_t msgType = getMessageType(blob);
switch(msgType) {
case 1: return make_unique<MsgDerived1>(std::move(blob));
case 2: return make_unique<MsgDerived2>(std::move(blob));
//etc.
}
}
If you want the messages to return the data, but for example MsgType1 should make it all lower case, and MsgTyp2 all upper case you could make a virtual function in MsgBase called, for example,
virtual char *getData();
and this function should be reimplemented in child classes so that it does with the data what you want it to do. This way when you call this function on base class pointer, you will get reimplemented functionality, depending to what type the actual pointer is, at the moment of calling.

Conversions between object types

What I'm trying to do:
void startApp() {
//create validator
MedValidator* val = new MedValidator();
//create reporsitory
MedicineRepository* repo= new MedRepo() ;
//create controller
Control wh(repo, val);
...}
Here is a view at the used types:
class MedValidator
{
public:
void validate(const Medicine& s) throw(MedException);
};
class MedicineRepository
{
public: virtual void addMed(Medicine s) ;
};
class MedRepo : public MedicineRepository{
public:void addMed(Medicine s);
protected:
Vector<Medicine*> MedList;
};
I get Multiple markers at this line
- candidates are:
- no matching function for call to 'Control::Control(MedicineRepository&,
MedValidator*&)' at startApp() when I'm declaring wh
class Control {
public:
Control(MedRepo* repo, MedValidator* validator);};
How can I fix this?I hope the amount of code is enough,if it's needed more I'll add.
The constructor for Control takes a MedRepo* argument:
Control(MedRepo* repo, MedValidator* validator);};
But you are passing a MedicineRepository*:
MedicineRepository* repo= new MedRepo() ;
//create controller
Control wh(repo, val);
Also, don't use exception specifications, they're bad.
Your problem is that MedRepo is a MedicineRepository but MedicineRepository is not a MedRepo. You can't substitute a base class object where a derived class object is expected, only the reverse (safely, anyway). You need to figure out if you need a pointer to that specific derived class or if a pointer to any derived class is okay. For the former keep your code how it is and send it a MedRepo object. If any derived class will do (i.e. you're only accessing methods from the base class) then change Control to accept the base class instead.

What's a good safe way to initialise memory for types I don't yet know about?

I started thinking about this after receiving an answer for this question. This is a bit tricky to explain, but I'll do my best.
I'm building a small(ish) 2D game engine. There are certain requirements that I need to satisfy, since this engine has to "work" with existing code that others have written for a different engine. Some change to existing code is inevitable, but I want to minimise it.
Users of my engine need to define entities called "gadgets". These are basically structs containing shapes and other state variables. These "gadgets" fall into classes, e.g. they may decide to define an icon gadget or a button gadget - or whatever.
They will also define a message handler for that class of gadgets.
E.g.
typedef struct
{
shape shapelist[5];
int num_options;
}interface;
static void interface_message_handler( interface * myself, message * msg )
{
switch( msg->type )
{
case NEW_MSG:
{
interface_descriptor * desc = msg->desc;
// initialize myself with contents of this message.
...
}
break;
....
}
}
Users have already given me the corresponding message handler function and also the number of bytes in a interface object. And they can then ask the engine to create new instances of their gadgets via IDs e.g:
engine->CreateNewGadget( interface_gadget_class_ID, welcome_interface_ID );
where interface_gadget_class_ID is the ID for that class of gadgets and welcome_interface_ID is the instance ID. At some point during CreateNewGadget I need to a) allocate memory to hold a new gadget and then call the gadget class's message handler on it, with a NEW_MSG so that it can initialize itself.
The problem is, if all I'm doing is allocating memory - that memory is uninitialized (and that means all the struct members are uninitialized - so if interface contains a vector, for example, then I'm going to get some wierd results if the message handler does anything with it ).
To avoid wierd results caused by doing stuff to unintialized memory, I really need to call a constructor for that memory as well before passing it to the gadget's message handler function.
e.g in the case of interface:
pfunc(new (memory) interface);
But my question is, if I have no knowledge of the types that users are creating, how can I do that?
// We create a typedef that refers to a function pointer
// which is a function that returns an interface pointer
typedef interface * (*GadgetFactory)(void);
// we'll actually create these functions by using this template function
// Different version of this function will produce different classes.
template<typename T>
interface * create_object()
{
return new T;
}
// This function takes care of setting everything up.
template<typename T>
void RegisterGadgetType(int gadget_type_id)
{
// Get outselves a copy of a pointer to the function that will make the object
GadgetFactory factory = create_object<T>;
// store factory somewhere
}
interface * CreateGadget(int gadget_type_id)
{
// get factory
GadgetFactory factory;
// factory will give me the actual object type I need.
return (*factory)();
}
RegisterGadgetType<S>(2);
CreateGadget(2);
as i see it, you always know because interface_gadget_class_ID defines the type to create.
you create a base c++ class: (corresponds to class interface in your example). this base class contains all of data members which are used by every interface subclass (that is, every gadget).
the base class also declares all methods common to every gadget. example: each gadget is able to receive a call handleMessage. handleMessage is pure virtual, because this method is the subclasses' role to fulfill.
then you extend/subclass to support the stuff you have to do with each gadget's specialization. at this point, you add the members and methods specific to each gadget subclass.
CreateNewGadget serves as a factory for all your subclasses, where the arguments determine which class you will create.
from there, c++ will handle construction/destruction, allocation sizes, etc..
if you're allowing plugins with their own factories in your engine, then you'll need another level, where third parties register their custom types and inherit from your base(s).
here's a simple layout of the interfaces (in non-compiled pseudo code):
namespace MONGadgets {
class t_interface {
protected:
t_interface(/* ... */);
public:
virtual ~t_interface();
/* each subclass must override handleMessage */
virtual t_result handleMessage(const t_message& message) = 0;
};
namespace InterfaceSubclasses {
class t_gadget1 : public t_interface {
public:
t_gadget1(const welcome_interface_ID& welcome);
virtual ~t_gadget1();
virtual t_result handleMessage(const t_message& message) {
std::cout << "t_gadget1\n";
}
/* gadget1 has no specific instance variables or methods to declare */
};
class t_gadget2 : public t_interface {
public:
t_gadget2(const welcome_interface_ID& welcome);
virtual ~t_gadget2();
virtual t_result handleMessage(const t_message& message) {
std::cout << "t_gadget2\n";
}
private:
/* here is an example of a method specific to gadget2: */
void drawShape(const unsigned& idx);
private:
/* here is gadget2's unique data: */
shape shapelist[5];
int num_options;
};
namespace ClassID {
enum { Gadget1 = 1, Gadget2 = 2 };
}
}
/* replaced by virtual t_result t_interface::handleMessage(const t_message&)
- static void interface_message_handler( interface * myself, message * msg );
*/
class t_gadget_factory {
public:
t_interface* CreateNewGadget(const interface_gadget_class_ID& classID, const welcome_interface_ID& welcome) {
switch (classID) {
case InterfaceSubclasses::ClassID::Gadget1 :
return new InterfaceSubclasses::gadget1(welcome);
case InterfaceSubclasses::ClassID::Gadget2 :
return new InterfaceSubclasses::gadget2(welcome);
/* ... */
}
}
};
}
Example code (ignoring my other suggestion, about factories and virtual functions):
typedef struct
{
shape shapelist[5];
int num_options;
} interface;
static void interface_message_handler( void * myself, message * msg )
{
switch( msg->type )
{
case NEW_MSG:
{
interface *self = new (myself) interface;
interface_descriptor * desc = msg->desc;
// initialize myself with contents of this message.
...
}
break;
case OTHER_MSG:
{
interface *self = static_cast<interface*>(myself);
...
}
break;
....
}
}
Then your CreateNewGadget code does:
void *ptr = malloc(some_amount);
msg newmsg;
newmsg.type = NEW_MSG;
// other fields
some_message_handler(ptr, &msg);
// now we have an initialized object, that we can add to our tree or whatever.
The less horrible version is more like this:
struct gadgetinterface {
virtual ~gadgetinterface() {}
virtual void handle_message(msg *) = 0;
};
struct mygadget : gadgetinterface {
void handle_message(msg *m) {
// no need for NEW_MSG, just do other messages
}
};
gadgetinterface *mygadget_factory(some parameters) {
// use some parameters, either passed to constructor or afterwards
return new mygadget();
}
Then we register a pointer to mygadget_factory with the gadget manager, and CreateNewGadget does this:
gadgetinterface *some_factory(some parameters); // that's it!
Where some_factory is the function pointer that was registered, so in the case of this gadget type, it points to mygadget_factory.