c++ template class member specialization and inheritance - c++

I would like to write down a set of classes in which there are:
a pure virtual class that wraps an object of any kind and the relate getter for it.
one or more classes for every kind of object I need, extending the virtual one and overriding the getter in order to specialize it.
A template class solution for the wrapper seems to fit the case but I have to use it in two different contexts:
the first one is not aware of wrapper implementations. In this case I should declare a Wrapper<AnyObj> var; with AnyObj standing for any class name (like ? in Java). As far as I know, you can't do this in c++.
the second one is restricted to a particular wrapper implementation. In this case I need the getter to return the wrapped object with the exact type (rather than downcasting it).
If I'm right I cannot use a template class and, moreover, the wrapper won't have a protected: T* wrappedObject member.
I don't know if I'm stuck in the Java approach, wrongly thinking from the beginning, or missing something.
Any suggestion is appreciated.

Related

How to set a class function to behave as another class function

I have two classes, ClassWorking and TemplateClass, they are not related in any way.
Is there a way to say, I want the function TemplateGenerate() from my TemplateClass now to behave like the function generate() from my class ClassWorking.
Like a (this function does not exist) SetFunctionBehavior(&templateClassRef->templateGenerate, &classWorkingRef->generate)
I know I can use function pointer to make TemplateClass receive a pointer and call it in the class, but that not what I want.
It's more something like a LD_Preload, to replace the inner of function without having to re-write it and without inherit from a class who has it.
to be a little more explicit let's see it more like a node construction for class
TemplateClass can have multiple functions but not with the same behaviour
- TemplateClass
- TemplateGenerate() {will do this}
- TemplateGenerate() {will do that}
- TemplateGenerate() {will do like that}
and when I declare my class pointer templateClassRef->TemplateGenerate = TemplateGenerate() {will do that}
but not with a lambda :)
The point is to have something really generic without having to re-create a class for each need, for example I could have a class:
TemplateGenerate
- function A {A1 Behavior} Functiun B {B1 Behavoir} Functiun C {C1 Behavior}
{A2 Behavior} {B2 Behavoir} {C2 Behavior}
{A3 Behavior} {B3 Behavoir} {C3 Behavior}
And when I declare my function I say I take A1,B2,C3 or A1,B1,C2
The method ClassWorking::generate is a function that takes a ClassWorking and does stuff.
A function that has the same behaviour also takes a ClassWorking. That is part of what the function does.
As TemplateClass is unrelated to ClassWorking, a method TemplateClass::templateGenerate that "behaves alike" ClassWorking::generate cannot succeed; you don't have a ClassWorking, so one of the prequisites of ClassWorking::generate isn't being fullfilled.
Now, it might be the case that the implementation of ClassWorking::generate doesn't actually need an instance of ClassWorking. It might need something else.
But for the compiler to know this, you have to change the method from being a method of ClassWorking to being something else. For example, you could write a free function generate that takes an argument what you actually need, and have ClassWorking::generate call that free function.
Then calling the free function generate from a stub method TemplateClass::templateGenerate becomes trivial.
C++ does not support "do what I mean" or "read my mind". You actually have to tell the compiler what you want to happen. And types matter in C++, so you cannot wire up a method on one class to another class without also telling C++ how the types relate.
There are languages where types are looser and you actually can grab a method off one class and glue it onto another. These are generally interpreted languages with much heavier runtime object models than C++; members in this language are implemented as property bags of named values, values are actually variants at runtime, etc.
You can implement that kind of object in C++, but it isn't a "native" C++ object, and you'll have to write a pile of glue code (some of which could be hidden by metaprogramming). That is far from a beginner task, and usually a bad idea; if you need the flexibility of scripting languages, just use a scripting language.
One way is to use composition. Define an interface
struct Interface
{
virtual void/*maybe*/ templateGenerate(/*maybe*/) /*const?*/ = 0;
};
Then implement
struct ClassWorkingImpl : Interface, ClassWorking
{
// ToDo - delegate all the constructors
// ToDo - implement templateGenerate using the method in ClassWorking
};
and similarly for TemplateClass.
Then you instantiate ClassWorkingImpl &c. rather than ClassWorking. And you can call the interface method templateGenerate on either.

C++ inheritance pattern

I am after your opinion on how best to implement an inheritance pattern in C++. I have two base classes, say
class fooBase{
protected:
barBase* b;
};
class barBase{};
where fooBase has a barBase. I intend to put these classes in a library, so that wherever I have a fooBase it can use its barBase member.
I now intend to create a specialisation of these in a specific program
class fooSpec : public fooBase{};
class barSpec : public barBase{};
Now I want fooSpec::b to point to a barSpec instead of a barBase. I know that I can just initialise b with a new barSpec, but this would require me to cast the pointer to a barSpec whenever I wanted to use specific functions in the specialisation wouldn't it?
Is there another way that this is often acheived?
Cheers.
Create a method in your specclass to cast the b into the special version.
That way instead of casting it all the time, it looks like a getter.
On the other hand OO is about programming towards interfaces and not objects. So what you are doing here looks like programming towards objects. But the is difficult to see as this example is purely theoretical.
You may consider the template solution:
template <class T>
class fooBase{
protected:
T* b;
};
and then use it as
class fooSpec : public fooBase<barSpec>{};
while ordinarily, the base would be used as fooBase<barBase>.
Is this what you want?
Normally we create a function that has the cast and returns the pointer -- and use that instead of the member directly.
Now I want fooSpec::b to point to a barSpec instead of a barBase.
There's no such thing as fooSpec::b. b belongs to fooBase, and your new class fooSpec is a (specialization of) a fooBase. You can't change the fact that b, a fooBase member, is of type barBase. This is a property of all the instances of fooBase that you can't invalidate in the particular subset of instances concerned by your specialization.
I know that I can just initialise b with a new barSpec, but this would
require me to cast the pointer to a barSpec whenever I wanted to use
specific functions in the specialisation wouldn't it?
Yes and no. Yes, you need to do that cast; but no, you don't need to do it every time. You can encapsulated in a function of fooSpec.
Is there another way that this is often acheived?
Not that I'm aware of.
this would require me to cast the pointer to a barSpec whenever I wanted to use specific functions in the specialisation wouldn't it?
That depends on whether the method you are trying to invoke is defined in the superclass and whether it is virtual.
You need to cast the pointer before invoking a method if one of the following is true...
The method belongs to the subclass only
The superclass has an implementation of the method and the subclass's implementation does not override the implementation in the superclass. This amounts to a question of whether the function is a virtual function.
Avoid data members in non-leaf classes, use pure virtual getters instead. If you follow this simple rule, your problem solves itself automatically.
This also makes most non-leaf classes automatically abstract, which may seem like an undue burden at first, but you get used to it and eventually realize it's a Good Thing.
Like most rules, this one is not absolute and needs to be broken now and then, but in general it's a good rule to follow. Give it a try.
If it looks too extreme, you may try one of the design patterns that deal with dual hierarchies such as Stairway to Heaven.

Is there any way to avoid declaring virtual methods when storing (children) pointers?

I have run into an annoying problem lately, and I am not satisfied with my own workaround: I have a program that maintains a vector of pointers to a base class, and I am storing there all kind of children object-pointers. Now, each child class has methods of their own, and the main program may or not may call these methods, depending on the type of object (note though that they all heavily use common methods of the base class, so this justify inheritance).
I have found useful to have an "object identifier" to check the class type (and then either call the method or not), which is already not very beautiful, but this is not the main inconvenience. The main inconvenience is that, if I want to actually be able to call a derived class method using the base class pointer (or even just store the pointer in the pointer array), then one need to declare the derived methods as virtual in the base class.
Make sense from the C++ coding point of view.. but this is not practical in my case (from the development point of view), because I am planning to create many different children classes in different files, perhaps made by different people, and I don't want to tweak/maintain the base class each time, to add virtual methods!
How to do this? Essentially, what I am asking (I guess) is how to implement something like Objective-C NSArrays - if you send a message to an object that does not implement the method, well, nothing happens.
regards
Instead of this:
// variant A: declare everything in the base class
void DoStuff_A(Base* b) {
if (b->TypeId() == DERIVED_1)
b->DoDerived1Stuff();
else if if (b->TypeId() == DERIVED_2)
b->DoDerived12Stuff();
}
or this:
// variant B: declare nothing in the base class
void DoStuff_B(Base* b) {
if (b->TypeId() == DERIVED_1)
(dynamic_cast<Derived1*>(b))->DoDerived1Stuff();
else if if (b->TypeId() == DERIVED_2)
(dynamic_cast<Derived2*>(b))->DoDerived12Stuff();
}
do this:
// variant C: declare the right thing in the base class
b->DoStuff();
Note there's a single virtual function in the base per stuff that has to be done.
If you find yourself in a situation where you are more comfortable with variants A or B then with variant C, stop and rethink your design. You are coupling components too tightly and in the end it will backfire.
I am planning to create many different children classes in different
files, perhaps made by different people, and I don't want to
tweak/maintain the base class each time, to add virtual methods!
You are OK with tweaking DoStuff each time a derived class is added, but tweaking Base is a no-no. May I ask why?
If your design does not fit in either A, B or C pattern, show what you have, for clairvoyance is a rare feat these days.
You can do what you describe in C++, but not using functions. It is, by the way, kind of horrible but I suppose there might be cases in which it's a legitimate approach.
First way of doing this:
Define a function with a signature something like boost::variant parseMessage(std::string, std::vector<boost::variant>); and perhaps a string of convenience functions with common signatures on the base class and include a message lookup table on the base class which takes functors. In each class constructor add its messages to the message table and the parseMessage function then parcels off each message to the right function on the class.
It's ugly and slow but it should work.
Second way of doing this:
Define the virtual functions further down the hierarchy so if you want to add int foo(bar*); you first add a class that defines it as virtual and then ensure every class that wants to define int foo(bar*); inherit from it. You can then use dynamic_cast to ensure that the pointer you are looking at inherits from this class before trying to call int foo(bar*);. Possible these interface adding classes could be pure virtual so they can be mixed in to various points using multiple inheritance, but that may have its own problems.
This is less flexible than the first way and requires the classes that implement a function to be linked to each other. Oh, and it's still ugly.
But mostly I suggest you try and write C++ code like C++ code not Objective-C code.
This can be solved by adding some sort of introspection capabilities and meta object system. This talk Metadata and reflection in C++ — Jeff Tucker demonstrates how to do this using c++'s template meta programming.
If you don't want to go to the trouble of implementing one yourself, then it would be easier to use an existing one such as Qt's meta object system. Note that this solution does not work with multiple inheritance due to limitations in the meta object compiler: QObject Multiple Inheritance.
With that installed, you can query for the presence of methods and call them. This is quite tedious to do by hand, so the easiest way to call such a methods is using the signal and slot mechanism.
There is also GObject which is quite simmilar and there are others.
If you are planning to create many different children classes in different files, perhaps made by different people, and also I would guess you don't want to change your main code for every child class. Then I think what you need to do in your base class is to define several (not to many) virtual functions (with empty implementation) BUT those functions should be used to mark a time in the logic where they are called like "AfterInseart" or "BeforeSorting", Etc.
Usually there are not to many places in the logic you wish a derived classes to perform there own logic.

Root base class in C++

Every object in .NET inherits (directly or indirectly) from the common root base "Object". Is there such a common object root in C++? How do I pass any object to a function?
public void DoSomeStuff(object o) { ... }
EDIT: To clarify, the purpose: In that function I want to invoke a pointer to member function. For that I need the object instance and pointer to the required function. To simplify readability I want to make a wrapper containing the both required information. I'm not sure if that is the best way, but it is the background idea.
There is no common base class; but using a something like boost::any or more generally a template based approach is preferred over a void*.
There is no common root class. Use either void* to pass any object into a function, or better define some base class.
Template functions are present and avoid the need for such root parent of all classes.
template <class T>
void DoSomeStuff(T const &t) {
// Do the stuff with t...
t.callTheFunction();
}
If all your objects have a member function callTheFunction(), then you got the exactly same behavior than having a root base class, with the same requirement (all your classes have a function with that name).
In addition, you got the additional benefit of being able to specialize the template function DoSomeStuff() for some classes that are not yours, and could not inherit your virtual member function.
For that I need the object instance and pointer to the required function.
That sounds a lot like "delegates". First, you definitely will need to define a common base class for all the objects that you want to call. In C++ you can use multiple inheritance if the object already belong to some other hierarchy.
Then have a read through Member Functions and the Fastest Possible C++ Delegates which is an excellent in-depth article on the topic of delegates (which are an object and member function pointer bound together). Using the header file described in that article, you can create delegates and easily call them just like regular function pointers.
Sorry - there is no root base object in C++. But you can define your own for all your classes.
There is no common base class in C++. However, there are already libraries that allow you to call member functions as delegates. You can try using boost::function together with boost::bind or boost::lambda.
You'd at least depend on a minimum c++ runtime if there were a root object implemented in c++. This is undesirable sometimes.

Practical Uses for the "Curiously Recurring Template Pattern"

What are some practical uses for the "Curiously Recurring Template Pattern"? The "counted class" example commonly shown just isn't a convincing example to me.
Simulated dynamic binding.
Avoiding the cost of virtual function calls while retaining some of the hierarchical benefits is an enormous win for the subsystems where it can be done in the project I am currently working on.
It's also especially useful for mixins (by which I mean classes you inherit from to provide functionality) which themselves need to know what type they are operating on (and hence need to be templates).
In Effective C++, Scott Meyers provides as an example a class template NewHandlerSupport<T>. This contains a static method to override the new handler for a particular class (in the same way that std::set_new_handler does for the default operator new), and an operator new which uses the handler. In order to provide a per-type handler, the parent class needs to know what type it is acting on, so it needs to be a class template. The template parameter is the child class.
You couldn't really do this without CRTP, since you need the NewHandlerSupport template to be instantiated separately, with a separate static data member to store the current new_handler, per class that uses it.
Obviously the whole example is extremely non-thread-safe, but it illustrates the point.
Meyers suggests that CRTP might be thought of as "Do It For Me". I'd say this is generally the case for any mixin, and CRTP applies in the case where you need a mixin template rather than just a mixin class.
The CRTP gets a lot less curious if you consider that the subclass type that is passed to the superclass is only needed at time of method expansion.
So then all types are defined.
You just need the pattern to import the symbolic subclass type into the superclass, but it is just a forward declaration - as all formal template param types are by definition - as far as the superclass is concerned.
We use in a somewhat modified form, passing the subclass in a traits type structure to the superclass to make it possible for the superclass to return objects of the derived type. The application is a library for geometric calculus ( points, vectors, lines, boxes ) where all the generic functionality is implemented in the superclass, and the subclass just defines a specific type : CFltPoint inherits from TGenPoint. Also CFltPoint existed before TGenPoint, so subclassing was a natural way of refactoring this.
Generally it is used for polymorphic-like patterns where you do not need to be able to choose the derived class at runtime, only at compile time. This can save the overhead of the virtual function call at runtime.
For a real-world library use of CRTP, look at ATL and WTL (wtl.sf.net). It is used extensively there for compile-time polymorphism.