Let me tell you the problem I have. I'm designing a set of classes to control a digital device. This device can work in two modes of operation. In the first mode it can perform a specific set of operations, and in the second mode it can perform another set of operations (with possibly some common operations between the two). I can also change the mode of the device on the run, so I can swap between the two modes if necessary. Independently of the mode, the device use the same set of registers.
I was thinking in solve this problem with one base class for each mode, so I can have objects of mode 1 when I need the first set of operations and objects of mode 2 when I need the second set of operations. Then I could derive a class from these two base classes, so I can have objects that perform all the operations.
The problem with my design is that the two base classes have some common functions and references to the same registers. Since I can't prevent inheritance of members I would have duplicates in the derived class. I know I can choose which duplicate to access with the scope operator, but I still think this a bad design.
So my question is: is there an idiomatic way of solve this problem?
If there isn't a right or easy way of solving this, I'm thinking about design 3 hierarchically independently classes. I would have some duplicate code, but that is not a big problem, right?
Code below (simplified) for illustration:
class mode1
{
protected:
volatile uint8_t& reg1;
volatile uint8_t& reg2;
uint8_t data;
public:
virtual void operation1() final { // do something }
virtual void operation2() final { // do something }
virtual void operation3() final { // do something }
};
class mode2
{
protected:
volatile uint8_t& reg1;
volatile uint8_t& reg2;
uint8_t data;
public:
virtual void operation4() final { // do something }
virtual void operation2() final { // do something }
virtual void operation5() final { // do something }
};
class mode1and2 : public mode1, public mode2
{
public:
void operation6() { // do something }
void operation7() { // do something }
};
Note modes 1 and 2 have operation2 and all the data members in common.
I'd put the common parts of mode1 and mode2 in a common base class, let's say Common, comprising then your data and member function operation2. Then, together with virtual inheritance, you can have two views on the same data, even at the same time if needed.
class common {
friend class mode1;
friend class mode2;
protected:
volatile uint8_t& reg1;
volatile uint8_t& reg2;
uint8_t data;
public:
virtual void operation2() final { // do something
};
};
class mode1 : public virtual common
{
public:
virtual void operation1() final { // do something
};
virtual void operation3() final { // do something }
};
};
class mode2 : public virtual common
{
public:
virtual void operation4() final { // do something
}
virtual void operation5() final { // do something
}
};
class mode1and2 : public mode1, public mode2
{
public:
void operation6() { // do something }
};
void operation7() { // do something }
};
};
The state design pattern looks like a good candidate for your case.
As a minimal, working example:
#include<memory>
#include<iostream>
struct Behavior {
virtual void f() = 0;
virtual void g() = 0;
};
struct NullBehavior: Behavior {
void f() override {}
void g() override {}
};
struct Mode1: Behavior {
void f() override { std::cout << "mode 1 - f" << std::endl; }
void g() override { std::cout << "mode 1 - g" << std::endl; }
};
struct Mode2: Behavior {
void f() override { std::cout << "mode 2 - f" << std::endl; }
void g() override { std::cout << "mode 2 - g" << std::endl; }
};
struct Device {
template<typename B>
void set() { behavior = std::unique_ptr<Behavior>{new B}; }
void f() { behavior->f(); }
void g() { behavior->g(); }
private:
std::unique_ptr<Behavior> behavior{new NullBehavior};
};
int main() {
Device device;
device.f();
device.g();
device.set<Mode1>();
device.f();
device.g();
device.set<Mode2>();
device.f();
device.g();
}
From the point of view of the user of the device, it doesn't matter what's the mode you are using. Anyway, as requested, you can dynamically change it whenever you want and your device will start to work with the new mode from that point on.
Preferring composition over inheritance solves the issue due the conflicting names. Delegating everything from the outer class to the inner state does the rest.
Note that, if you want to share methods between states, nothing prevents you from putting them in the base class.
A slightly different version helps you sharing also data between the twos:
struct Data {
volatile uint8_t& reg1;
volatile uint8_t& reg2;
uint8_t data;
};
struct Behavior {
virtual void f(Data &) = 0;
virtual void g(Data &) = 0;
};
struct NullBehavior: Behavior {
void f(Data &) override {}
void g(Data &) override {}
};
struct Mode1: Behavior {
void f(Data &) override { /* ... */ }
void g(Data &) override { /* ... */ }
};
struct Mode2: Behavior {
void f(Data &) override { /* ... */ }
void g(Data &) override { /* ... */ }
};
struct Device {
template<typename B>
void set() { behavior = std::unique_ptr<Behavior>{new B}; }
void f() { behavior->f(data); }
void g() { behavior->g(data); }
private:
Data data{};
std::unique_ptr<Behavior> behavior{new NullBehavior};
};
All those parameters that are unique for a specific mode can be part of the class definition or put within Data and ignored if you are working in a different mode.
Related
I've been trying to find an answer to this question but I couldn't (I don't even know how to properly formulate this) so I decided to write my first post ever on StackOverflow =).
The context is the following:
I have this parent class:
class Parent
{
public:
Parent(){};
void foo(void)
{
//Do some common things
bar();
//Do some more common things
};
protected:
virtual void bar(void) = 0;
};
And I want to create an indefinite amount of derived Childs:
class Child1 : public Parent
{
public:
Child1() : Parent(), child1Variable(0) {};
protected:
virtual void bar(void) = 0;
private:
uint32_t child1Variable;
};
class Child2 : public Parent
{
public:
Child2() : Parent(), child2Variable(0) {};
protected:
virtual void bar(void) = 0;
private:
uint32_t child2Variable;
};
.
.
.
class ChildN : public Parent
{
public:
ChildN() : Parent(), childNVariable(0) {};
protected:
virtual void bar(void) = 0;
private:
uint32_t childNVariable;
};
The reason being mainly not repeating the code in Parent's foo()
Then I would like to create my final instantiable classes as, for instance:
class ExampleFinal : public Child1, public Child3, public Child27
{
//How to define Child1::bar(), Child3::bar() and Child27::bar() ??
private:
void bar(void); //????
};
So the questions are:
How can I define the method for (abusing notation) ExampleFinal::Child1::bar, ExampleFinal::Child3::bar, ...
Am I so stuck on this that I'm overlooking a much simpler solution?
The final goal is being able to do something like:
ExampleFinal test;
test.Child1::foo(); //should end up on "ExampleFinal::Child1::bar"
test.Child3::foo(); //should end up on "ExampleFinal::Child3::bar"
Thanks!
Implementing ExampleFinal::bar() (side-note: bar(void) is a C-ism which has no use in C++) will override all of the bars you have declared at once. If you want to have different versions, you'll need to interpose another layer of classes:
struct GrandChild1 : Child1 {
void bar() override { /*...*/ }
};
// And so on...
struct ExampleFinal : GrandChild1, GrandChild3, GrandChild27 {
// Nothing needed here.
};
Then the behaviour you described will work. Be aware, though, that your inheritance graph means that an ExampleFinal has one Parent subobject per Child. This is not an issue in itself but might not model what you want -- maybe you need virtual inheritance here, but beware of the rabbit hole.
If you want to keep the overrides for all ChildN::bars inside ExampleFinal, you can add tag-dispatching to discern them, at the cost of one more virtual call:
struct Parent {
void foo() {
bar();
};
protected:
template <class Child>
struct tag { };
virtual void bar() = 0;
};
struct Child1 : Parent {
protected:
virtual void bar(tag<Child1>) = 0;
void bar() final override {
return bar(tag<Child1>{});
}
int child1Var;
};
struct Child2 : Parent {
protected:
virtual void bar(tag<Child2>) = 0;
void bar() final override {
return bar(tag<Child2>{});
}
int child2Var;
};
struct ExampleFinal : Child1, Child2 {
protected:
using Parent::tag;
void bar(tag<Child1>) final override {
std::cout << "Child1::bar\n";
}
void bar(tag<Child2>) final override {
std::cout << "Child2::bar\n";
}
};
Note that the bar() to bar(tag<ChildN>) bridge can easily be hidden behind a macro. If you want to avoid the cost of the second virtual call, a CRTP can also be applied here.
I am looking for an elegant solution for my case. I tried to find a design pattern that specified and offers solution for this case but i failed to find one.
I have a base class that uses to store general object and later Invoke it.
I want the execution will be separated into two parts:
A must have part which will always take place (do1st()).
User defined code (do2nd()).
For example:
class InvokeBase
{
public:
InvokeBase(void *ptr) : context_(ptr) {}
virtual ~InvokeBase () {}
void operator()() = 0;
protected:
void do1st() {//Mandatory code to execute for every InvokeBase type when calling operator()};
void * context_;
};
class InvokeDerived : public InvokeBase
{
public:
InvokeDerived(void *ptr) : base(ptr){}
virtual ~InvokeDerived();
void do2nd() {//User defined code}
void operator()()
{
do1st(); // << How to force this execution?
do2nd();
}
};
void main()
{
InvokeBase *t = new InvokeDerived();
t(); // << here i want the execution order will be do1st and then do2nd.
}
The trick is that i want do1st will execute always, that i will not have to call it from InvokeDerived. I want to allow the user to inherit from InvokeBase with the guarantee that do1st will always be called when invoking the operator().
This is the template method pattern: split a function with semi-flexible behavior accross the class hierarchy into multiple parts, and make virtual only the ones that change:
class InvokeBase
{
public:
InvokeBase(void *ptr) : context_(ptr) {}
virtual ~InvokeBase () {}
void operator()() // this is non-virtual (this is the template method)
{
do1st();
do2nd(); // this resolves to virtual call
}
protected:
void do1st() { /* fixed code here */ };
virtual void do2nd() = 0; // variable part here
void * context_;
};
class InvokeDerived : public InvokeBase
{
public:
InvokeDerived(void *ptr) : base(ptr){}
virtual ~InvokeDerived() = default;
protected:
void do2nd() override
{
// code speciffic to InvokeDerived here
}
};
Please consider the following (simplified) class hierarchy and processing functions:
struct msgBase
{
virtual int msgType() const=0;
};
struct msgType1:public msgBase
{
virtual int msgType() const{return 1;}
};
struct msgType2:public msgBase
{
virtual int msgType() const {return 2;}
};
void process(const msgType1& mt1)
{
// processing for message type 1
}
void process(const msgType2& mt2)
{
// processing for message type 2
}
void process(const msgBase& mbase)
{
switch(mbase.msgType())
{
case 1:
process(static_cast<const msgType1&>(mbase));
break;
case 2:
process(static_cast<const msgType2&>(mbase));
break;
}
}
In an integrated design, msgBase would be given a virtual "process" method, to avoid needing to iterate over the types.
If it's not possible or desirable to modify any of the classes, are there any alternatives to iterating over the types?
I've experimented with a decorator/factory pattern where a parallel hierarchy of classes encapsulates the given classes, and implements the necessary virtual functions, but this results in an awful lot of boilerplate, and the factory function still needs to iterate over the types!
I could replace the switch statement with a series of dyamic_casts, but that still leaves the same weaknesses.
As requested by Simon, here is what I mean by CRTP:
typedef <class Derived>
struct msgBase
{
virtual void process(){
// redirect the call to the derived class's process()
static_cast<Derived*>(this) -> process();
};
struct msgType1:public msgBase<msgType1>
{
void process(){
// process as per type-1
}
};
struct msgType2:public msgBase<msgType1>
{
void process(){
// process as per type-2
}
};
What's happening here? Consider this case:
msgBase* msg = new msgType1();
msg->process();
normally (without CRTP) this would only call msgBase::process(). But now, msgBase "knows" about msgType1 using the template, so it is redirected to msgType1::process at compile time.
Something like this could work:
These classes are used to do the casting automatically:
struct dispatcher_base {
virtual void process(const msgBase&) = 0;
};
template <class T>
struct dispatcher_impl : dispatcher_base {
void process(const msgBase& b) override {
::process(static_cast<const T&>(b));
}
};
We'll store them in a map:
auto g_table = std::map<int, std::unique_ptr<dispatcher_base>>{};
But now you have to initialize this table somewhere:
template <class T>
void register_msg() {
g_table[T{}.msgType()].reset(new dispatcher_impl<T>{});
}
...
register_msg<msgType1>();
register_msg<msgType2>();
You can add an assert to register_msg to make sure that msgTypes are unique.
Your process function will look like this:
void process(const msgBase& b) {
assert(g_table.find(b.msgType()) != g_table.end());
g_table[b.msgType()]->process(b);
}
You can replace assert with any other logic of course.
If you can't modify the classes then you can use decorators to get polymorphic type deduction.
struct DecorBase {
DecorBase(msgBase& b) : b_(b) {}
virtual ~DecorBase() {}
virtual void process() = 0;
msgBase& b_;
};
struct DecorType1 : public DecorBase {
DecorType1(msgType1& t1) : DecorBase(t1) {}
void process() override {
std::cout << "Processing Type 1" << std::endl;
}
};
struct DecorType2 : public DecorBase {
DecorType2(msgType2& t2) : DecorBase(t2) {}
void process() override {
std::cout << "Processing Type 2" << std::endl;
}
};
And use it like this:
msgType1 t1;
msgType2 t2;
DecorType1 dt1(t1); // Wrap objects in respective decorator.
DecorType2 dt2(t2);
DecorBase& base = dt2;
base.process(); // Uses polymorphism to call function in derived type.
This will require you to write a decorator for every derived type but at least you don't have to iterate over all types during the function call.
I once implemented a state machine like this:
class Player
{
public:
int Run();
int Jump();
int Stop();
private:
class State
{
public:
virtual int Run() = 0;
virtual int Jump() = 0;
virtual int Stop() = 0;
};
class StandingState : public State
{
virtual int Run() { /*...*/ }
virtual int Jump() { /*...*/ }
virtual int Stop() { /*...*/ }
};
class RunningState : public State
{
virtual int Run() { /*...*/ }
virtual int Jump() { /*...*/ }
virtual int Stop() { /*...*/ }
};
// More states go here!
std::list<State*> states;
State* currentState;
};
int Player::Run()
{
int result = m_currentState->Run();
// do something with result
}
int Player::Jump()
{
int result = m_currentState->Jump();
// do something with result
}
int Player::Stop()
{
int result = m_currentState->Stop();
// do something with result
}
Fairly textbook I should think: Player delegates the calls from outside to its current State object, and does something with the result (possibly transitioning to another state). Essentially, each state knows how a given action affects it, but it's up to the state machine to wire the various states together. I found this to be a good separation of concerns.
But I'm seeing a possibility for abstraction here. The entire system is defined by the interface of the State class:
Both the state machine and the substates implement State
The state machine keeps a pointer to all possible States and the current State
Whatever method of State is called on the state machine, it is undiscerningly forwarded to the current state.
So, we can totally make this a class template, right? Look:
template< class StateInterface >
class StateMachine : public StateInterface
{
// public methods already declared in StateInterface
protected:
std::list<StateInterface*> states;
void AddState(StateInterface* state);
StateInterface* currentState;
};
class PlayerStateInterface
{
public:
virtual int Run() = 0;
virtual int Jump() = 0;
virtual int Stop() = 0;
};
class Player : public StateMachine< PlayerStateInterface >
{
public:
virtual int Run() { currentState->Run(); /* do stuff */ }
virtual int Jump() { currentState->Jump(); /* do stuff */ }
virtual int Stop() { currentState->Stop(); /* do stuff */ }
};
Of the above points, this has 1 and 2 covered, but what about 3? I still have to manually delegate the calls to the current state in the concrete state machine implementation. Is there a way to move that functionality to the StateMachine template? Can I somehow express that whenever a method of StateInterface is called on StateMachine it should call the same method on currentState, when I don't know the names or signatures of StateInterface's methods?
If you're looking for a general answer to the case where Run, Jump, and Stop have different signatures, I don't know if there's a good solution. However, in your example they all have the same signature, which suggests to me that the following approach might work:
#include <iostream>
class AbstractState
{
public:
virtual void write1() = 0;
virtual void write2() = 0;
};
class State1: public AbstractState
{
public:
virtual void write1() { std::cout << "1-1" << std::endl; }
virtual void write2() { std::cout << "1-2" << std::endl; }
};
class State2: public AbstractState
{
public:
virtual void write1() { std::cout << "2-1" << std::endl; }
virtual void write2() { std::cout << "2-2" << std::endl; }
};
template <typename StateInterface>
class Player
{
public:
Player(StateInterface *s_):
s(s_)
{
}
void setState(StateInterface *s_)
{
s = s_;
}
void execute(void (StateInterface::*method)())
{
(s->*method)();
}
private:
StateInterface *s;
};
int main()
{
State1 s1;
State2 s2;
Player<AbstractState> p(&s1);
p.execute(&AbstractState::write1);
p.execute(&AbstractState::write2);
p.setState(&s2);
p.execute(&AbstractState::write1);
p.execute(&AbstractState::write2);
return 0;
}
I was able to compile and run this with GCC 4.5.2 and got the expected result, namely:
1-1
1-2
2-1
2-2
As I said, I'm not sure that there's a good way to extend this to the case where the different member functions of AbstractState take different parameters or return different values, and there may be other drawbacks that I haven't considered yet. It isn't quite as nice as what I think you were hoping to find, but hopefully this will at least serve as a good starting point.
I'm working with some code where I have the following setup.
struct data
{
void change_safe_member(){}
void read_data(){}
void change_unsafe_member(){}
};
struct data_processor
{
std::shared_ptr<data> get_data(){}
void return_data(std::shared_ptr<data> my_data)
{
my_data->change_unsafe_member(); // ONLY data_processor should call this function.
}
};
struct client
{
void foo(std::shared_ptr<data_processor>& my_processor)
{
auto my_data = my_processor->get_data();
my_data->change_safe_member();
//my_data->change_unsafe_member(); SHOULD NOT BE POSSIBLE TO CALL
my_processor->return_data(my_data);
}
};
The change_unsafe_member should only be used internally by the processor so I would like to hide it or disable it for the client. But I don't know of any nice ways of doing this without resorting to ugly casts...
struct internal_data
{
void change_unsafe_member(){}
};
struct data : public internal_data
{
void change_safe_member(){}
void read_data(){}
};
struct data_processor
{
std::shared_ptr<data> get_data(){}
void return_data(std::shared_ptr<data> my_data)
{
auto internal_data = std::static_pointer_cast<internal_data>(my_data);
internal_data->change_unsafe_member();
}
};
Anyone know of a good pattern to use in situations like this? Maybe visitor pattern or something similar?
EDIT:
As pointed out in the comments one could declare friend classes, there is however one problem... the following will not work.
struct data
{
void change_safe_member(){}
void read_data(){}
private:
friend class data_processor;
virtual void change_unsafe_member(){}
};
struct data_decorator : public data
{
data_decorator(const std::shared_ptr<data>& decoratee) : decoratee_(decoratee){}
void change_safe_member(){decoratee_->change_safe_member();}
void read_data(){decoratee_->read_data();}
private:
virtual void change_unsafe_member()
{
std::cout << "Hello!"; // Add functionality
decoratee_->change_unsafe_member(); // Won't work... compiler error
}
std::shared_ptr<data> decoratee_;
};
// Another example
struct data_group_decorator : public data
{
data_group_decorator (const std::vector<std::shared_ptr<data>>& decoratees) : decoratees_(decoratees){}
void change_safe_member(){decoratee_->change_safe_member();}
void read_data(){decoratee_->read_data();}
private:
virtual void change_unsafe_member()
{
for(size_t n = 0; n < decoratees_.size(); ++n)
decoratees_[n]->change_unsafe_member(); // Won't work... compiler error
}
std::vector<std::shared_ptr<data>> decoratees_;;
};
You can make this happen with inheritance.
struct Y;
struct X {
friend struct Y;
private:
change_unsafe_member() {}
};
struct Y {
protected:
change_unsafe_member(X& x) { x.change_unsafe_member(); }
};
struct some_other : Y {
X x;
change_safe_member() { change_unsafe_member(x); }
};
Any class that inherits from Y can gain X's friendship for any functions that Y defines as effectively forwards from X.
Your last example looks like what you're really asking for is inherited friendship; i.e. you want to have a hierarchy of decorator - derived classes which are all allowed to call the private member function in data. That's answered (with "generally no") elsewhere:
Why does C++ not allow inherited friendship?
Polymorphism might provide some relief in your specific scenario, make class data_decorator an "almost pure" virtual base class, with the only nonvirtual member being a protected change_unsafe_member(), and make that in turn a friend of class data. All decorators would inherit from data_decorator, and call its protected nonvirtual member.