Need help converting Graphics32 Delphi sample to C++ - c++

USING BDS2006:
I'm trying to convert the Graphics32 Resampler_ex example in C++, but i can't even understand what happens in some codes, or how to rewrite that code in C++.
In that sample there's a combobox to choose what resampler to use:
This is the Deplhi code in his OnChange event:
procedure TfmResamplersExample.KernelClassNamesListClick(Sender: TObject);
var
Index: Integer;
begin
Index := KernelClassNamesList.ItemIndex;
if Src.Resampler is TKernelResampler then
with TKernelResampler(Src.Resampler) do
begin
Kernel := TCustomKernelClass(KernelList[Index]).Create;
LbParameter.Visible := (Kernel is TAlbrechtKernel) or
{$IFDEF Ex}
(Kernel is TGaussianKernel) or
(Kernel is TKaiserBesselKernel) or
(Kernel is TNutallKernel) or
(Kernel is TBurgessKernel) or
(Kernel is TBlackmanHarrisKernel) or
(Kernel is TLawreyKernel) or
{$ENDIF}
(Kernel is TSinshKernel);
gbParameter.Visible := LbParameter.Visible;
SetKernelParameter(Kernel);
CurveImage.Repaint;
end;
end;
where:
{ TClassList }
{ This is a class that maintains a list of classes. }
TClassList = class(TList)
protected
function GetItems(Index: Integer): TClass;
procedure SetItems(Index: Integer; AClass: TClass);
public
function Add(AClass: TClass): Integer;
function Extract(Item: TClass): TClass;
function Remove(AClass: TClass): Integer;
function IndexOf(AClass: TClass): Integer;
function First: TClass;
function Last: TClass;
function Find(AClassName: string): TClass;
procedure GetClassNames(Strings: TStrings);
procedure Insert(Index: Integer; AClass: TClass);
property Items[Index: Integer]: TClass read GetItems write SetItems; default;
end;
ResamplerList: TClassList;
My problems are on this line
Kernel := TCustomKernelClass(KernelList[Index]).Create;
How can i convert this line in C++?
EDIT AFTER THE COMMENTS AND THE ANWERS:
Ok, seems beyond my undertanding. For my purposes, it will suffice to be able to replicate what this code do without too much hassle.
Could it be possible to instantiate the right class just using a switch based on the itemindex?
These are the 4 classes i should instantiate:
class DELPHICLASS TNearestResampler;
class PASCALIMPLEMENTATION TNearestResampler : public Gr32::TCustomResampler
{
typedef Gr32::TCustomResampler inherited;
[...]
}
class DELPHICLASS TLinearResampler;
class PASCALIMPLEMENTATION TLinearResampler : public Gr32::TCustomResampler
{
typedef Gr32::TCustomResampler inherited;
[...]
};
class DELPHICLASS TDraftResampler;
class PASCALIMPLEMENTATION TDraftResampler : public TLinearResampler
{
typedef TLinearResampler inherited;
[...]
};
class DELPHICLASS TKernelResampler;
class PASCALIMPLEMENTATION TKernelResampler : public Gr32::TCustomResampler
{
typedef Gr32::TCustomResampler inherited;
[...]
};
I don't ever get how could i assign one of them to "Kernel"....

The Delphi code relies on Delphi virtual constructors. This functionality does not exist in C++.
If you wanted to translate the code literally then you'd need to find a way to instantiate the class by calling the virtual Delphi constructor. You cannot do that in C++ so you'd need some Delphi code to glue it all together. Remy's answer here shows how to use __classid() to obtain a Delphi metaclass. You'd then need to pass that metaclass to a Delphi function to perform the instantiation.
Frankly I would view that as being a rather convoluted solution to the problem. Instead I think I'd replace the class list with a function list. The functions in the list would have the task of instantiating a new instance of a kernel. So instead of adding a class to the list, you add a function that creates a new instance of the class. In fact you might want a map between name and function, it all depends on your needs.

From what I remember from Delphi programming, this will actually instantiate the same type of class, which currently is kept in KernelList[index] and then cast it back to TCustomKernelClass. AFAIK there is no such mechanism in C++, but you can solve it by introducing virtual CreateInstance method:
class TCustomKernelClass
{
public:
virtual TCustomKernelClass * CreateInstance() = 0;
}
class TDerivedKernelClass
{
public:
TCustomKernelClass * CreateInstance()
{
return new TDerivedKernelClass();
}
}
You'll have to introduce some changes in the classes though. I doubt it can be solved directly in C++.
Edit: In response to comments
Ok, I see now, there are class definitions kept in that list. Since RTTI in C++ is not as extensive as in Delphi, I'd change the code to (written from memory, may not compile):
std::vector<std::function<TBaseKernelClass(void)>> KernelList;
KernelList.push_back([]() { return new TDerivedKernelClass(); });
// (...)
Kernel = KernelList[index]();

Related

Alternative to inheritance from a generic parameter in Swift

I'm quite new to Swift and recently noticed that you cannot inherit from a generic in Swift, e.g.
class MyClass<T> : T {}
is not valid in Swift 3 (see question this question).
Here is the problem I was hoping to solve with the above construct:
protocol Backend {
func operationA(operand: Int)
}
class ConcreteBackend : Backend {
func operationA(operand: Int) {
// ...
}
// Some other functions and/or custom initializers
// ...
}
class EnhancedBackend<T : Backend> : T {
override func operationA(operand: Int) {
// do something smart here
super.operationA(operand: modifiedOperand)
}
}
Basically EnhancedBackend does something smart with the input of operationA and then passes it to the actual implementation of Backend.
I'm using inheritance here instead of composition, because ConcreteBackend might have some public properties, functions and initializers that are not specified in the protocol (because they are only related to the concrete implementation) that I want to also expose with EnhancedBackend.
Without inheritance this would not be possible.
A C++ implementation might look like
// Using concepts here instead of protocols
class ConrecteBackend {
public:
void operationA(int operand) { .... }
}
template<class T>
class EnhancedBackend : public T {
using Base = T;
public:
// Ensure T is a model of the Backend concept
static_assert(isModelOfConceptBackend<T>::value,
"Template parameter is not a model of concept Backend");
// Ensure all constructors of Base can be used
template<class ...Args, typename = std::enable_if_t<
std::is_constructible<Base, Args...>::value>>
inline EnhancedBackend(Args &&...args) : Base(std::forward<Args>(args)...) {}
void operationA(int operand) {
// ...
Base::operationA(operand);
}
};
So with C++ it's quite simple to solve the problem. But at the moment I have no clue how to implement in with (pure) Swift 3.
Swift's generics are not the same as C++ templates which are closer to pre processing macros than Swift's type semantics.
There are however a number of ways to achieve similar results. One way if to use variables to reference functions that need customized dispatching rules:
for example:
protocol Backend:class
{
var operationA:(Int) -> () { get set }
func performOperationA(_ : Int) -> ()
}
class ConcreteBackend : Backend
{
lazy var operationA:(Int) -> () = self.performOperationA
func performOperationA(_ : Int) -> ()
{
// ...
}
// Some other functions and/or custom initializers
// ...
}
extension Backend
{
var enhancedForTesting:Self
{
operationA = testing_OperationA
return self
}
func testing_OperationA(_ operand:Int) -> ()
{
let modifiedOperand = operand + 1
performOperationA(modifiedOperand)
}
}
let enhancedBackend = ConcreteBackend().enhancedForTesting
By using a variable to reference the function's implementation, it becomes possible to dynamically change the behaviour of operationA at runtime and for specific instances.
In this example, the enhancements are added to the Backend protocol but they could also have been set by an independent function or even another class that has its own particular kind of altered behaviour.
When using this approach, the instance has all the attributes and functions of the concrete class while implementing the enhanced behaviour for the altered functions of the protocol.
Creating the enhanced instance uses a syntax that is as simple as (if not simpler than) a generic class constructor:
// for example:
let instance = ConcreteBackend(...).enhanced
// rather than:
let instance = EnhancedBackend<ConcreteBackEnd>(...)

Adapter pattern : Why would we need to subclass the Adaptee?

For an Object Adapter design, GoF states :
makes it harder to override Adaptee behavior. It will require subclassing Adaptee and making Adapter refer to the subclass rather than the Adaptee itself
My question is that why is this subclassing required when we are creating the clases as follows :
class Target {
public :
virtual void op() = 0 ;
} ;
class Adaptee {
public :
void adapteeOp() {cout<<"adaptee op\n" ;}
} ;
class Adapter : public Target {
Adaptee *adaptee ;
public :
Adapter(Adaptee *a) : adaptee(a) {}
void op() {
// added behavior
cout<<"added behavior\n" ;
adaptee->adapteeOp() ;
// more added behavior
cout<<"more added behavior\n" ;
}
} ;
main() { //client
Adapter adapter(new Adaptee) ;
adapter.op() ;
}
I have not been able to appreciate the requirement for subclassing as mentioned by GoF when I am able to override the behavior here also.
Please explain what is the point that I am missing out.
I have not been able to appreciate the requirement for subclassing as mentioned by GoF when I am able to override the behavior here also.
I see your confusion. Your example is too simple as it only contains cout statements. I wouldn't qualify adding cout statements before and after a call to one of Adaptees methods as adding any significant behavior. You need to consider more complex scenarios.
Imagine that you want to add newFunctionality to the Adaptee that uses the protected data from Adaptee. You can't modify the Adaptee so the only option you have is to subclass it.
class NewAdaptee : public Adaptee {
public :
void adapteeOp() {
cout<<"adaptee op\n" ; //step 3
}
void newFunctionality() { //use protected members from Adaptee }
} ;
The above code demonstrates a more complex use case of adding functionality to the Adaptee where subclassing is the only way to achieve this. So you now want to start using this new Adaptee in your Adapter. If you go with the object adapter option, you will need to start using a NewAdaptee reference in the Adaptor
class Adapter : public Target {
NewAdaptee *adaptee ;
//more code follows
}
This has the immediate issue that your Adapter can no longer be passed any direct subclasses of Adaptee. This is what they mean when they say It will require subclassing Adaptee and making Adapter refer to the subclass rather than the Adaptee itself. This would take away the advantage of the object adapter approach which was to allow a single adapter to work with all the subclasses of the Adaptee.
Note : In the class adapter approach, NewAdaptee would actually be your adapter and would also inherit Target.

Implementing C++ -to-lua observer pattern?

I have an observer (or "listener") pattern implemented in my code as such:
struct EntityListener
{
public:
virtual void entityModified(Entity& e) = 0;
};
class Entity
{
public:
Entity();
void setListener(EntityListener* listener);
private:
EntityListener* m_listener;
};
Now, this works in C++; the Entity class calls the entityModified() method whenever it needs. Now, I'd like to transfer some of the functionality to Lua, and among those function points is this listener callback. The entities are now created from the Lua scripts. The question is, how do I achieve the listener functionality in Lua?
For example, the Lua script currently does something like this:
function initializeEntity()
-- The entity object is actually created in C++ by the helper
Entity = Helper.createEntity()
-- Here I'd like to hook a Lua function as the Entity's listener
end
One possible solution is to have a LuaListener class in your C++ code that contains a "pointer" to the Lua function, and a Lua-specific setListener function that is called from the Lua script that takes a Lua function as argument, and creates a LuaListener instance and passes that to the actual C++ setListener.
So the Lua code would look something like
function onModified(entity)
-- ...
end
function initializeEntity()
entity = Helper.createEntity()
entity.setListener(onModified)
end
And the C++ code would look something like (pseudoish-code only):
class LuaListener : public EntityListener
{
private:
lua_State* state;
std::string funcName;
public:
void entityModified(Entity& e)
{
// Call function `funcName` in `state`, passing `e` as argument
}
};
class LuaEntity : public Entity
{
public:
void setListenerLua(state, funcName, ...)
{
Entity::setListener(new LuaListener(state, funcName, ...));
}
};

Delphi typcast tlist items C++ approach

Hi I have one question regarding some type casting approaches. I am translating some Delphi files to C++. I have delphi declaration of class which is derived from TList and it's a base class for other derived classes.
type TBaseItem = class (TObject)
public
procedure SomeProcedure; virtual; abstract;
end;
Type TBaseClass = class(TList)
private
function GetItem(Index: Integer): TBaseItem;
procedure SetItem(Value: TBaseItem; Index: Integer);
public
property Items[Index: Integer]: TBaseItem read GetItem write SetItem;
end;
function TBaseClass.GetItem(Index: Integer): TBaseItem;
begin
Result := TBaseItem(inherited Items[Index]);
end;
procedure TBaseClass.SetItem(Value: TBaseItem; Index: Integer);
begin
inherited Items[Index] := Value;
end;
This are two base classe TBaseItem and TBaseClass. So here are declared new classes TchildItem which is derived from TBaseItem and TChildClass which is derived from TBaseClass. TChildItem is overriding method SomeMethod and what is more important is that TChildtClass is overriding property Items in a way that now we are returning TParentItem items insted of TBaseItem.
type TChildItem = class (TBaseItem)
public
procedure SomeProcedure; override;
end;
type TChildClass = class(TBaseClass)
private
function GetItem(Index: Integer): TChildItem;
procedure SetItem(Value: TChildItem; Index: Integer);
public
property Items[Index: Integer]: TChildItemread GetItem write SetItem;
end;
function TChildClass .GetItem(Index: Integer): TChildItem;
begin
Result := TChildItem(inherited Items[Index]);
end;
procedure TChildClass.SetItem(Value: TChildItem; Index: Integer);
begin
inherited Items[Index] := Value;
end;
With this example I wanted to show how easy can be done deriving classes and overriding properties. Getting proper type of item out of a list is simply done by calling parents (base) property Item and typecast it to proper type. This is delphi apporach.
I wonder how can I translate this part of code to C++. Currently I declared a new base class which is not derived from any class and it has public var Items which is
class TBaseItem{
virtual void SomeMethod();
}
class TBaseClass {
public:
vector<TBaseItem> Items;
};
class TChildItem : public TBaseItem{
}
class TChildClass : public TBaseClass {
};
and then use
return (TChildItem) Items[Idx]
That means I would like to access parent's (TBaseClass) public variables such as that vector Items and typecast it to proper type... My first impression is that I might be going into wrong direction with that Delphi approach.
What do you suggest? How should I go with that?
THANK YOU VERY MUCH!
The Delphi code is old and pre-dates generics, the Delphi analogue to C++ templates. In modern Delphi code those list classes would simply not exist. Instead one would use TList<TBaseItem> and TList<TChildItem>.
In C++ code you would simply use vector<TBaseItem*> and vector<TChildItem*>. There is simply no point in your C++ translation to implement TBaseClass and TChildClass.
I would also correct your terminology. Delphi properties cannot be overriden. The new property in TChildClass is just that, a new property.

Plugins/modules shared by multiple programs

I want to define plugin like objects for my program. They should look like this:
class ModuleBase
{
public :
void baseFunction1();
void baseFunction2();
...
virtual void init() = 0;
virtual void finalize() = 0;
};
class SpecificModule : public ModuleBase
{
public :
virtual void doSpecificTask() = 0;
};
Thus I will have SpecificModule implementations:
class ConcreteSpecificModule1 : public SpecificModule
{
public :
void init();
void finalize();
void doSpecificTask();
};
In order to mask implementation and complexity, I want my modules to see the underlying system through a facade Interface :
class SystemViewForSpecificModule
{
public :
virtual SystemData& getData(//some parameters) = 0;
virtual void doSystemAction1() = 0;
virtual void doSystemAction2() = 0;
...
};
Finally I want to be able to make several programs that can deal with Module and / or SpecificModule instances.
Considering I have prog1, prog2, and prog3, I will have to implement
Prog1View, Prog2View and Prog3View as concrete implementations of SystemViewForSpecificModule interface.
Additionally, I have to consider the following case :
Prog2 will embed Prog1 and I want to be able to do this :
instantiate the SpecificModule instances
run the prog1 part that make calls to SpecificModule::doSpecificTask();
run the prog2 part that also call SpecificModule::doSpecificTask();
My question is: How to pass / store the reference (or pointer) to the system in the SpecificModule instances ?
1 - Storing the reference at construction time :
thus the SpecificModule interface should like
class SpecificModule : public ModuleBase
{
SystemViewForSpecificModule& m_sys;
public :
SpecificModule(SystemViewForSpecificModule& sys):m_sys(sys){}
virtual void doSpecificTask() = 0;
};
This is a pleasant way to achieve my problem, but don't forget that in prog2 I have first to
run my modules with prog1, thus I have to switch from SystemViewForSpecificModule implementation dynamically in this case.
(+) Modules can access to system during their whole life and all method can get access to it.
(-) Once the reference set, it can not be changed
We can consider that using a reference is not a good solution, or use something like this:
class SystemView : public SystemViewForSpecificModule
{
SystemViewForSpecificModule* concreteSystem;
public
SystemView(SystemViewForSpecificModule& sys)
{concreteSystem = &sys;}
void setSystem(SystemViewForSpecificModule& sys)
{concreteSystem = &sys;}
void doSystemAction1()
{concreteSystem->doSystemAction1();}
...
}
This way, the module doesn't even know that the implementation has changed
However, I'm afraid it will reduce performance due to extra vtable access.
2 - Using a setter to specify the system view
The SpecificModule interface should like:
class SpecificModule : public ModuleBase
{
SystemViewForSpecificModule* m_sys;
public :
setSystem(SystemViewForSpecificModule& sys){m_sys = &sys;}
virtual void doSpecificTask() = 0;
};
That seems to be a convenient solution but I don't like the fact that the module has:
the knowing of this change
to handle this change
to check the validity of the pointer before using it
3 - Passing references to SpecificModule methods
At least the SpecificModule interface will look like that:
class SpecificModule : public ModuleBase
{
virtual void doSpecificTask(SystemViewForSpecificModule& sys) = 0;
};
I don't like to pass the same reference 10000 times to the same function (both prog1 and prog2 part will call it lot of times).
Another bad point for this solution is: I don't have access to the system view in the ModuleBase methods (such as init() and finalize()). And obviously, moving them to the subclasses would reduce the inheritance interest.
What solution would you use in this example case (I hope to see other solutions than the 3 presented)?