C++ pure virtual method defined at run-time - c++

Not sure if the name is very telling but here goes.
I am interfacing to an API that requires a base class to be inherited and a lot of pure virtual methods to be defined.
For good programming practice, I want these methods to be defined in different (sub) classes.
Currently, I use a facade/wrapper (kind of both) class, that inherits the base class, instantiates the sub-classes, and calls the necessary methods of these instantiated classes:
#include <cstdio>
class Base
{
public:
virtual void reqImplementation( void ) = 0;
};
class APIImplementation
{
private:
Base * ptr_;
public:
APIImplementation( Base * ptr ) :
ptr_( ptr )
{
ptr_->reqImplementation();
}
};
class MyImplementation
{
private:
APIImplementation * api_;
public:
void reqImplementation( void )
{
printf("Hello World!\n");
}
MyImplementation( APIImplementation * api ) : api_( api ) {}
};
class MyFacade : public Base
{
private:
MyImplementation * my_impl_;
APIImplementation * api_;
void reqImplementation( void )
{
my_impl_->reqImplementation();
}
public:
MyFacade( void )
{
api_ = new APIImplementation( this );
my_impl_ = new MyImplementation( api_ );
}
};
int main( void )
{
MyFacade my_facade;
return 0;
}
Is there any way to implement the pure virtual functions in the sub-classes instantiated within this facade/wrapper? Or, alternately, what would be good practice for something like this? I want something similar to this (I know it clearly doesn't work at the moment):
#include <cstdio>
class Base
{
public:
virtual void reqImplementation( void ) = 0;
};
class APIImplementation
{
private:
Base * ptr_;
public:
APIImplementation( Base * ptr ) :
ptr_( ptr )
{
ptr_->reqImplementation();
}
};
class MyImplementation : public Base
{
private:
APIImplementation * api_;
public:
void reqImplementation( void )
{
printf("Hello World!\n");
}
MyImplementation( APIImplementation * api ) : api_( api ) {}
};
class MyFacade : public Base
{
private:
MyImplementation * my_impl_;
APIImplementation * api_;
public:
MyFacade( void )
{
api_ = new APIImplementation( this );
my_impl_ = new MyImplementation( api_ );
}
};
int main( void )
{
MyFacade my_facade;
return 0;
}
Note the API source is open, so I can change these pure virtual methods to anything else, however the code is quite exhaustive, so I'd rather small changes than significant ones.

If I got you right, you need a virtual inheritance. Here's an example
#include <iostream>
using namespace std;
// base class with lots of methods (two, actually)
struct Base {
virtual void f() = 0;
virtual void g() = 0;
};
// here's a class with implementation of f
struct ImplementationPart1 : public virtual Base {
virtual void f() {
cout << 4;
}
};
// here's a class with implementation of g
struct ImplementationPart2 : public virtual Base {
virtual void g() {
cout << 2;
}
};
// here's a class with all the implementations
struct Implementation : public ImplementationPart1, public ImplementationPart2 {};
int main() {
// Implementation inherits from Base, yes
Base *x = new Implementation();
// everything works, as expected
x->f();
x->g();
}
Live example.

Related

Architecture of sub-classes in C++

I learn C++ OOP-paradigm and want to ask related question:
Assumption
We have a base class:
class Base {
public:
virtual SomeType PowerMethod() { return SomeType{} };
}
We have a variable target and subclass which realizes some calculations with target variable based on the constructor's parameter (simple calculations or complicated calcs):
class Calc : public Base {
public: // using only public access to simplify real code structure
SomeType target;
void Simple() { target = 1; };
void Complex(){ target = 10000; };
explicit Calc(bool isSimple) {
if(isSimple)
Simple();
else
Complex();
}
};
Question
How to optimally realize two classes which based on different methods (Simple or Complex) but provide the same functionality of PowerMethod()?
My solution
class SimpleCalc : public Calc {
bool isSimple = true;
public:
SomeType PowerMethod() override {
Calc CalcInstance(isSimple);
return CalcInstance.target;
};
};
class ComplexCalc : public Calc {
bool isSimple = false;
public:
SomeType PowerMethod() override {
Calc CalcInstance(isSimple);
return CalcInstance.target;
};
};
This solution is pretty "ugly" and I want to ask you how to make it more readable.
Thank you!
I think that in your code, you didn't mean to craete a new Calc object, but instead call it on the superclass. This can be done like so:
Calc::Simple();
You can override the method PowerMethod, but still call the superclass's code:
virtual SomeType PowerMethod() override {
//do something
Base::PowerMethod();
}
If your problem is more complicated, and polymorphism and superclasses can't help you, you can always declare some method protected, so that only subclasses can access it. So, you could for example do this:
class Calc : public Base {
protected:
SomeType target;
void Simple() { target = 1; };
void Complex(){ target = 10000; };
public:
explicit Calc(bool isSimple) {
if(isSimple)
Simple();
else
Complex();
}
};
class SimpleCalc : public Calc {
public:
SomeType PowerMethod() override {
Calc::Simple();
return Calc::target;
};
};
class ComplexCalc : public Calc {
public:
SomeType PowerMethod() override {
Calc::Complex();
return Calc::target;
};
};
If your target is to learn OOP then you can use a factory design pattern to create your final calculator based on isSimple condition:
#include <iostream>
class Base
{
public:
Base()
{
target = 0;
}
int target;
virtual void PowerMethod() = 0;
};
class SimpleCalc : public Base
{
virtual void PowerMethod() { target = 0; }
};
class ComplexCalc : public Base
{
virtual void PowerMethod() { target = 1000; }
};
class CalcFactory
{
public:
virtual Base* createCalc(bool isSimple)
{
if (isSimple)
return new SimpleCalc();
else
return new ComplexCalc();
}
};
int main()
{
CalcFactory factory;
Base * base1 = factory.createCalc(true);
Base * base2 = factory.createCalc(false);
base1->PowerMethod();
base2->PowerMethod();
std::cout << base1->target << std::endl;
std::cout << base2->target << std::endl;
}

Requiring derived class to define a method

I am no doubt overlooking something basic but my implementation is obviously flawed.
I am trying to require a derived classes to implement a method being called in a base class.
class IClock
{
public:
virtual void OnTimeExpired() = 0;
}
class Clock : public IClock
{
... // ABC not implemented
}
class Application : public Clock
{
... // ABC not implemented
}
class DerivedApp : public Application
{
public:
virtual void OnTimeExpired() { ... }
}
I rarely use pure ABCs, so I thought by not defining the pure virtual method in Clock and Application, it would require all derivatives of Application to define the OnTimeExpired() method.
I discovered this will compile and link (MSVS-2017) and if DerivedApp does not implement the method, the Clock object will call an undefined method and crash.
Why does this compile without the pure virtual method being implemented?
How do I force derived Application classes to implement the OnTimeExpired() method?
EDIT: The crash was due to unrelated error - I apologize. Nevertheless the questions I ask are still applicable.
As requested here is a complete, buildable, minimal example:
IClock.h:
#pragma once
class IClock
{
public:
virtual void OnClockTime() = 0;
};
Clock.h:
#pragma once
#include "IClock.h"
class Clock : public IClock
{
public:
Clock();
virtual ~Clock();
void ClockUpdate();
virtual void OnClockTime();
private:
float elapsed_time;
};
Clock.cpp:
#include "Clock.h"
Clock::Clock()
: elapsed_time(0.0f)
{
}
Clock::~Clock()
{
}
void Clock::ClockUpdate()
{
elapsed_time += 0.0000001f; // small ticks for testing
if (elapsed_time >= 1.0f) {
OnClockTime();
elapsed_time -= 1.0f;
}
}
void Clock::OnClockTime()
{}
ApplicationBase.h
#pragma once
#include "Clock.h"
class ApplicationBase : public Clock
{
public:
ApplicationBase();
virtual ~ApplicationBase();
virtual void Init(){}
virtual void Run(){}
protected:
bool app_run;
};
ApplicationBase.cpp:
#include "ApplicationBase.h"
ApplicationBase::ApplicationBase()
: app_run(false)
{
}
ApplicationBase::~ApplicationBase()
{
}
DerivedApp.h:
#pragma once
#include "ApplicationBase.h"
class DerivedApp : public ApplicationBase
{
public:
DerivedApp();
virtual ~DerivedApp();
virtual void Init() {}
virtual void Run();
//virtual void OnClockTime();
};
DerivedApp.cpp:
#include "DerivedApp.h"
#include <iostream>
DerivedApp::DerivedApp()
{
}
DerivedApp::~DerivedApp()
{
}
void DerivedApp::Run()
{
app_run = true;
while (app_run) {
ClockUpdate();
}
}
//void DerivedApp::OnClockTime()
//{
// static int counts(0);
// std::cout << "Tick..." << std::endl;
// counts++;
// if (counts >= 10)
// app_run = false;
//}
main.cpp
#include "DerivedApp.h"
class App : public DerivedApp
{
public:
App(){}
~App(){}
};
int wmain(int argc, wchar_t * argv[])
{
App *app = new App();
app->Init();
app->Run();
delete app;
}
Thanks to those who requested a minimal working example, I built it and it works exactly as I had hoped. The complier will complain about no instantiation of the ABC in the App class. If I remove the comments from DerivedApp::OnClockTime() it compiles and runs the way I wish. Obviously my actual code is not following this model as I thought, so now I need to reexamine where I went wrong. Thanks.
There is no keyword in C++ that forces a class to override some method. However, by making OnTimeExpired() pure virtual you're making IClock an abstract class. Any classes deriving from IClock that do not implement OnTimeExpired() will automatically become an abstract class too, thus not allowing you to create objects of these classes. This means that your code as-is is completely legal unless you try to make objects of these classes
class AbstractBase {
public:
virtual void someFunc() = 0; // Purely Virtual
};
class AbstractDerived : public AbstractBase {
public:
void someOtherFunc();
// Still abstract because the following is not declared-defined
// void someFunc() override { ... }
};
class NonAbstractDerivedA : public AbstractBase { // Derived From Base
public:
void someFunc() override { /* do this class's implementation*/ }
};
class NonAbstractDerivedB : public AbstractDerived { // Derived From AbstractDerived
public:
void someFunc() override { /* do this class's implementation*/ }
};
uses:
#include "above"
int main() {
AbstractBase base; // compiler error
AbstractDerived derived; // compiler error
NonAbstractDerivedA derivedA; // should be okay
NonAbstractDerivedB derivedB; // should be okay
return 0;
}

How can I make a visitor pattern configurable in runtime?

Well, as you know, the design pattern Visitor has a "problem" similar to Abstract Factory problem: the more visitable classes I made, the more specific "visit" methods must create.
In the case of an abstract factory I made a solution using prototype of a product to "configure" the factory:
factory.h
class ExtensibleFactory
{
public:
~ExtensibleFactory();
void insertProductType(const string &nome, IProductPrototype *product);
void removeProductType(const string &nome);
IProductPrototype *createProduct(const string &nome);
private:
map<string, IProductPrototype *> m_productsHash;
};
factory.cpp
#include "extensiblefactory.h"
#include "iproductprototype.h"
ExtensibleFactory::~ExtensibleFactory()
{
for(map<string, IProductPrototype *>::iterator iter = this->m_productsHash.begin(); iter != this->m_productsHash.end(); ++iter)
{
delete iter->second;
}
this->m_productsHash.clear();
}
void ExtensibleFactory::insertProductType(const string &nome, IProductPrototype *product)
{
this->m_productsHash.insert(make_pair(nome, product));
}
void ExtensibleFactory::removeProductType(const string &nome)
{
delete this->m_productsHash[nome];
this->m_productsHash.erase(nome);
}
IProductPrototype *ExtensibleFactory::createProduct(const string &nome)
{
if ( this->m_productsHash.find(nome) == this->m_productsHash.end() )
{
return 0;
}
return this->m_productsHash[nome]->clone();
}
main.cpp
SanduichePrototype *sanduiche = new SanduichePrototype;
CarroPrototype *carro = new CarroPrototype;
ExtensibleFactory *fabrica = new ExtensibleFactory;
fabrica->insertProductType("sanduba", sanduiche);
fabrica->insertProductType("automovel", carro);
IProductPrototype *carro1 = fabrica->createProduct("automovel");
IProductPrototype *carro2 = fabrica->createProduct("automovel");
IProductPrototype *sanduiche1 = fabrica->createProduct("sanduba");
IProductPrototype *sanduiche2 = fabrica->createProduct("sanduba");
Now, consider this visitor and its elements:
ivisitor.h
class ElementA;
class ElementB;
class IVisitor
{
public:
virtual void visit(ElementA *elementA) = 0;
virtual void visit(ElementB *elementB) = 0;
};
ielement.h
class IVisitor;
class IElement
{
public:
virtual void accept(IVisitor *visitor) = 0;
};
elementa.h
class ElementA : public IElement
{
public:
virtual void accept(IVisitor *visitor);
};
elementb.h
class ElementB : public IElement
{
public:
virtual void accept(IVisitor *visitor);
};
If I want to add more elements I will have to add more methods do IVisitor interface.
I wish to know if it's possible to "configure" a visitor in runtime, in other words, I want to know if there are any solution to emulate the act of adding more methods to the IVisitor interface by configuring it just like I did to Factory pattern and, if so, which will be the possible solutions.
The action (visitor) object you want to pass around to objects will have to have hardwired at least knowledge of some common base class whose functionality it can use, and then as I see it there's not much point in dynamically registering visitable classes, because you need a dynamic dispatch anyway, e.g. dynamic_cast, and with that the need to list all supported classes in the common visitor interface, disappears.
Consider first a slight refactoring of your visitor pattern code – except for generality and naming and access it's the same as your code:
// Static visitor pattern.
template< class Visitable >
class Visitor_
{
template< class > friend class Visitable_impl_;
private:
virtual void visit( Visitable& ) {}
};
class A;
class B;
class I_visitor
: public Visitor_<A>
, public Visitor_<B>
{};
class I_visitable
{
public:
virtual void accept( I_visitor& ) = 0;
};
template< class Visitable >
class Visitable_impl_
: public I_visitable
{
public:
void accept( I_visitor& v )
override
{
static_cast<Visitor_<Visitable>&>( v ) // Cast for access.
.visit( static_cast<Visitable&>( *this ) ); // Cast for overload res.
}
};
class A: public Visitable_impl_<A> {};
class B: public Visitable_impl_<B> {};
#include <iostream>
using namespace std;
auto main()
-> int
{
class Action
: public I_visitor
{
private:
void visit( A& ) override { cout << "Visited an A." << endl; }
};
I_visitable&& a = A();
I_visitable&& b = B();
Action x;
a.accept( x ); b.accept( x );
}
Now we just replace the first static_cast with a dynamic_cast, and voilà:
// Dynamic visitor pattern.
template< class Visitable >
class Visitor_
{
template< class > friend class Visitable_impl_;
private:
virtual void visit( Visitable& ) {}
};
struct I_visitor { virtual ~I_visitor(){} }; // Note: no mention of A or B.
class I_visitable
{
public:
virtual void accept( I_visitor& ) = 0;
};
template< class Visitable >
class Visitable_impl_
: public I_visitable
{
public:
void accept( I_visitor& v )
override
{
if( auto p_visitor = dynamic_cast<Visitor_<Visitable>*>( &v ) )
{
p_visitor->visit( static_cast<Visitable&>( *this ) ); // Cast for overload res.
}
}
};
class A: public Visitable_impl_<A> {};
class B: public Visitable_impl_<B> {};
#include <iostream>
using namespace std;
auto main()
-> int
{
class Action
: public I_visitor
, public Visitor_<A>
{
private:
void visit( A& ) override { cout << "Visited an A." << endl; }
};
I_visitable&& a = A();
I_visitable&& b = B();
Action x;
a.accept( x ); b.accept( x );
}

How to change the behaviour of a method at runtime?

Short Version:
The main point is that the (complex) state of an instance can be changed by functions that are outside the definition of the class, as such the class can be extended to have all sorts of internal states without polluting the class defintion with many state-setters.
Assume the following code:
class bar
{
virtual void ChangeState()=0;
}
class foo:bar
{
private:
int b;
public:
void ChangeState() {b=3;}
}
What I would like to do is create different functions, then pass them to the function, at runtime, something like
foo.ChangeState(); //b is 3 now
void foo::(?)ChangeState2(){ b=2; };
foo.ChangeState=ChangeState2;
foo.ChangeState(); //b is 2 now
Can such a construct be implemented in C++, without the use of hacks?
Maybe, this will help:
#include <iostream>
namespace so
{
class B
{
friend void change_1( B * );
friend void change_2( B * );
friend void change_3( B * );
int i;
public:
B() : i{ 0 } {}
void change_state( void (*_function)( B * ) )
{
_function( this );
std::cout << i << std::endl;
}
};
void change_1( B * _object )
{
_object->i = -1;
}
void change_2( B * _object )
{
_object->i = -2;
}
void change_3( B * _object )
{
_object->i = -3;
}
} //namespace so
int main()
{
so::B b{ };
b.change_state( so::change_1 );
b.change_state( so::change_2 );
b.change_state( so::change_3 );
return( 0 );
}
Short answer: That's not possible.
What you can do is define multiple classes and choose between them based on some runtime condition. And of course, that object doesn't have to be the full class, we could do something like this:
class foo: public bar
{
private:
class ChangeState
{
public:
virtual void DoChangeState(foo *f) = 0;
};
class ChangeState2
{
public:
virtual void DoChangeState(foo *f) { f->b = 2 } ;
};
class ChangeState3 : public ChangeState
{
public:
virtual void DoChangeState(foo *f) { f->b = 3 } ;
};
ChangeState *stateChanger
public:
foo() { stateChanger = new ChangeState3; }
void SetStateChange2() { delete stateChanger; stateChanger = new ChangeState2; }
~foo() { delete stateChanger; }
void ChangeState() { stateChanger->DoChangeState(this); }
};
I'm sure there are other variations on this theme (and you probably should use a smart pointer).
You can't change the behaviour at runtime using the syntax you describe. You can however if you wish get something similar by using function pointers.
But if I understand what you are trying to accomplish correctly, I would look at implementing the strategy pattern

What's the simplest way to satisfy a pure abstract method with methods from other base classes

Edit: Per some comments, by simple I mean a) less code, b) easy to maintain, and c) hard to get wrong.
Edit #2: Also, using containment instead of private inheritance is not objectionable if it does indeed simplify the implementation of InterfaceImpl.
Currently, the only way I know to do this is to have the implementer define the abstract method and delegate the call to the target base type's method. Example:
#include <iostream>
#include <memory>
class Interface
{
public:
virtual void method1() = 0;
virtual void method2(int x) = 0;
};
class MethodOneImpl
{
private:
void method1(int x)
{ std::cout << "MethodOneImpl::method1() " << x << std::endl; }
public:
void method1() { method1(0); }
};
class MethodTwoImpl
{
public:
void myFunc(int x)
{ std::cout << "MethodTwoImpl::myFunc(x)" << x << std::endl; }
};
class InterfaceImpl : public Interface
, private MethodOneImpl
, private MethodTwoImpl
{
public:
virtual void method1() { MethodOneImpl::method1(); }
virtual void method2(int x) { MethodTwoImpl::myFunc(x); }
};
int main()
{
std::unique_ptr<Interface> inf;
inf.reset(new InterfaceImpl);
inf->method1();
inf->method2(0);
// This should be disallowed!
// std::unique_ptr<MethodOneImpl> moi;
// moi.reset(new InterfaceImpl);
}
At first, I thought that perhaps this might solve the problem:
class InterfaceImpl : public Interface
, private MethodOneImpl
, private MethodTwoImpl
{
public:
using MethodOneImpl::method1;
// Obviously this wouldn't work as the method names don't match.
//using MethodTwoImpl::???
};
The first using statement will make both MethodOneImpl::method1 methods be public, but it actually doesn't fulfill the contract with Interface, and it modifies the accessibility of MethodOneImpl::method1(int). And obviously we couldn't use this solution with method2 as the names don't match up.
FWIW, I have what I think is a solution, but it is not part of the standard at all (in other words it won't compile). I was thinking of making a proposal to the C++ committee; if anyone has any advice, I'd appreciate any comments below (but please dont' submit the advice as an answer).
An other option (at least if using MS VC++) is to use virtual inheritance:
struct MyInterface
{
virtual void Method1() = 0;
virtual void Method2() = 0;
};
class Method1Impl : public virtual MyInterface
{
virtual void Method1() { _tprintf( _T("Method1\n") ); }
};
class Method2Impl : public virtual MyInterface
{
virtual void Method2() { _tprintf( _T("Method2\n") ); }
};
class InterfaceImpl : public virtual MyInterface,
private Method1Impl,
private Method2Impl
{
};
void TestWeirdInterfaceImpl()
{
MyInterface* pItf = new InterfaceImpl();
pItf->Method1();
pItf->Method2();
}
While this seems to work and satisfy what you are looking for (asside from C4250 warning that you will have to suppress with a #pragma), this wouldn't be my approach. (I believe virtual inheritance is still not something that supported across all compilers, but I could be wrong).
I would probably go with containment and once boilerplate code is identifier, wrap it into some kind of macro map (similar to maps in ATL or MFC) that would make it really, really difficult to ever screw it up.
So this would be my macro approach:
struct MyInterface
{
virtual float Method1( int x ) = 0;
virtual int Method2( float a, float b ) = 0;
virtual void Method3( const TCHAR* sz ) = 0;
};
class Method1Impl
{
public:
float Method1( int x ) {
_tprintf( _T("Method1: %d\n"), x ); return 5.0;
}
};
class Method2and3Impl
{
public:
int Method2( float a, float b ) {
_tprintf( _T("Method2: %f, %f\n"), a, b ); return 666;
}
void Method3( const TCHAR* sz ) {
_tprintf( _T("Method3: %s"), sz );
}
};
#define DECLARE_METHOD0( MethodName, Obj, R ) \
virtual R MethodName() { return Obj.MethodName(); }
#define DECLARE_METHOD1( MethodName, Obj, R, A1 ) \
virtual R MethodName( A1 a1 ) { return Obj.MethodName( a1 ); }
#define DECLARE_METHOD2( MethodName, Obj, R, A1, A2 ) \
virtual R MethodName( A1 a1, A2 a2 ) { return Obj.MethodName( a1, a2 ); }
class InterfaceImpl : public MyInterface
{
public:
DECLARE_METHOD1( Method1, m_method1Impl, float, int );
DECLARE_METHOD2( Method2, m_method2and3Impl, int, float, float );
DECLARE_METHOD1( Method3, m_method2and3Impl, void, const TCHAR* );
private:
Method1Impl m_method1Impl;
Method2and3Impl m_method2and3Impl;
};
void TestWeirdInterfaceImpl()
{
MyInterface* pItf = new InterfaceImpl();
pItf->Method1( 86 );
pItf->Method2( 42.0, 24.0 );
pItf->Method3( _T("hi") );
}
Until C++ gods grace us with variadic macros, you'll have to declare one for each number of parameters you have. Also if you used multiple inheritance, potentially you wouldn't need the second "Obj" param, but as I've said before, I'd avoid multiple inheritance if there's another solution, which in this case is one extra param.
Yet a third option could be something that authors of Pragmatic Programmer seem to advocate a lot. If you have a ton of cookie cutter code that you don't want to repeat because, as you pointed out, it introduces human error. Define your own language and write a code generator script (python, perl...) to auto-create the actual code. In this case you could almost point at an interface, and have the script write the text out for you. I haven't tried doing this kind of thing myself, but lately have been wanting to use it somewhere just to see and evaluate the outcome.
This is sort of ugly and may bloat the executable size, but what about
#include <iostream>
class Interface
{
public:
virtual void method1() = 0;
virtual void method2(int x) = 0;
};
template<typename T>
class MethodOneImpl : public T
{
private:
void method1(int x)
{ std::cout << "MethodOneImpl::method1() " << x << std::endl; }
public:
void method1() { method1(0); }
};
template<typename T>
class MethodTwoImpl : public T
{
public:
void method2(int x)
{ std::cout << "MethodTwoImpl::myFunc(x)" << x << std::endl; }
};
class InterfaceImpl : public MethodTwoImpl<MethodOneImpl<Interface> >
{
};
int main()
{
InterfaceImpl impl;
impl.method1();
impl.method2(0);
}
class AbsInterface
{
// this is a simple interface class.
public:
virtual void Method1() = 0;
virtual void Method2() = 0;
};
class Functor1
{
public:
void operator () ()
{
printf("This Is Void Functor1");
}
};
class Functor2
{
public:
void operator () ()
{
printf("This Is void Functor2");
}
};
template <class T1, class T2>
class DerivedTemplateClass : public AbsInterface
{
public:
virtual void Method1() { T1()(); }
virtual void Method2() { T2()(); }
};
void main()
{
DerivedTemplateClass<Stratege1, Stratege2> instance;
instance.Method1();
instance.Method2();
}
as you can see, I used Functor.
You could work with template and functor.
It seems impossible to bring MethodOneImpl / MethodTwoImpl into the scope of Interface without having them inherit from Interface because they will not fill the Virtual Table if they don't. C++ misses something like the keyword implements from other languages.
So you are stuck with the virtual inheritence thing unless realize/accept that what you are looking for is just a bridge pattern, which does not satisfy requirement a) (you shall write more code), midly b) (code not necessarly difficult to maintain) and may satisfy c).
Here (another) possible solution (with only method though to reduce bloat)
class Interface
{ public:
virtual void method1() {return impl_->method1();}
private:
Interface() {}
protected:
struct Impl {
virtual void method1() = 0; };
std::shared_ptr<Impl> impl_;
Interface(const std::shared_ptr<Impl> &impl) : impl_(impl) {}
};
class InterfaceImpl : public Interface
{
struct Impl : public Interface::Impl {
void method1() { std::cout << "InterfaceImpl::method1() " << std::endl; } } ;
public:
InterfaceImpl() : Interface(std::shared_ptr<Impl> (new Impl)) {}
};
template <class T>
class GenericInterfaceImpl : public Interface {
struct Impl : public Interface::Impl {
Impl( T &t) : t_(t) {}
void method1() { t_.method1() ; }
T t_; };
public:
GenericInterfaceImpl() : Interface(std::shared_ptr<Impl> (new Impl(T()))) {}
};
struct AMethod1Impl {
void method1() { std::cout << "AMethod1Impl::method1() " << std::endl; } } ;
struct AnotherMethod1Impl_not_working {
void method1_not_present() { std::cout << "AnotherMethod1Impl_not_working ::method1_not_present() " << std::endl; } } ;
int main() {
// compilation of next line would fail
// (lame attempt to simulate ompilation fail when pure function not implemented)
// Interface inf;
std::unique_ptr<Interface> inf;
inf.reset(new InterfaceImpl);
inf->method1();
inf.reset(new GenericInterfaceImpl<AMethod1Impl>() );
inf->method1();
// compilation of next line would fail
// inf.reset(new GenericInterfaceImpl<AnotherMethod1Impl_not_working>() );
}
Does this serve your purpose?
It maintains the interface relationship and gives you maintainable code without having any consideration of client code.
Separating each method in functionoid and giving you the power to control the prototype of each method of the different base class.
#include <iostream>
#include <memory>
using namespace std;
//No Control over this.
class MethodOneImpl
{
private:
void method1(int x)
{ std::cout << "MethodOneImpl::method1() " << x << std::endl; }
public:
void method1() { method1(0); }
};
class MethodTwoImpl
{
public:
void myFunc(int x)
{ std::cout << "MethodTwoImpl::myFunc(x)" << x << std::endl; }
};
//*************************//
class Interface
{
public:
virtual void method1() = 0;
virtual void method2(int x) = 0;
};
//This is what i would do. //
class BaseFuncType
{
//no pure virtual
void Call()
{
throw "error";
}
void Call(int x)
{
throw "error";
}
};
class Method1: public BaseFuncType
{
auto_ptr<MethodOneImpl> MethodPtr;
public:
Method1()
{
MethodPtr.reset(new MethodOneImpl());
}
virtual int Call()
{
MethodPtr->method1();
}
};
class Method2: public BaseFuncType
{
auto_ptr<MethodTwoImpl> MethodPtr;
public:
Method2()
{
MethodPtr.reset(new MethodTwoImpl());
}
virtual int Call(int x)
{
MethodPtr->myFunc(x);
}
};
template <class T1>
class MethodFactory
{
private:
T1 methodObj;
public:
void CallMethod()
{
methodObj.Call();
}
void CallMethod(int x)
{
methodObj.Call(x);
}
};
class InterfaceImpl : public Interface
{
auto_ptr<MethodFactory> factory;
public:
virtual void method1()
{
factory.reset(new MethodFactory<Method1>());
factory->CallMethod();
}
virtual void method2(int x)
{
factory.reset(new MethodFactory<Method2>());
factory->CallMethod(x);
}
};
int main()
{
auto_ptr<Interface> inf;
inf.reset(new InterfaceImpl);
inf->method1();
inf->method2(10);
// This should be disallowed!
// std::unique_ptr<MethodOneImpl> moi;
// moi.reset(new InterfaceImpl);
}