C++ objects as parameters for interface methods - c++

For my C++ DLLs, I am using the factory pattern with abstract interfaces.
In the disadvantages section of this article, it says:
An abstract interface method cannot return or accept a regular C++ object as a parameter. It has be either a built-in type (like int, double, char*, etc.) or another abstract interface. It is the same limitation as for COM interfaces.
Could you elaborate what this means? What exactly can I not do and why?
Is there any further reading available on this matter?

This statement does not look accurate. Abstract interface method can return or accept C++ class instance (or its pointer) as parameter. There is no COM-like limitation here. It might be unsafe though in case caller/callee are built using different compiler settings, alignments, using different allocators etc. in which case the same C++ class is defined slightly differently and the mismatch might result in unexpected behavior. That is, it is not about "cannot", it is about it might lead to unobvious problems.
A frequent example of the problem in question is passing CString as a parameter:
function in dll doesn't receive CString argument value

Related

Does c++ standard specify how to pass this pointer to member functions?

Most everybody knows that class member receive the this pointer as the first "invisible" parameter of the function.
Is this specified in C++ standard? Can a certain compiler implementation pass it in a different way? Dedicated registry for example.
That's certainly how the very first versions of C++ were implemented (early C++ was transformed into C code), but be assured that the C++ standard does not mandate this.
Passing it as the last parameter value also seems feasible, and for virtual functions, some different technique altogether.

Advantages of 'pointer to a function' when using design patterns

In C++ we can make pointers to functions. So that we can pass a 'pointer to a function' as an argument to another function. When we consider about design patterns, are there any specific design patterns which specially take the advantage of using 'pointer to a function'?
Any design pattern that makes use of callbacks; such as visitor, strategy, and observer. Note that in C++, functors are also available to you and are generally preferred by the STL.
Most anything you can achieve with a pointer to a function, you can achieve with a functor with better optimization, or with virtual methods for better OO design. However, a pointer to a function is a requirement for narrow use cases where C code and C++ code are interfacing with each other. An OO design pattern can still allow C code to participate in the pattern. And, certain C interfaces only accept function pointers, so C++ code that use those APIs have to pass one in.
A function pointer is generally used as a means to call some code that is registered in some kind of subscription/publish model (event notification). For example, it could be used for the handle() method in the state pattern.
But, it can also be used as a simple hook to get code to run within a particular framework. For example, pthread_create takes a function pointer that is to be called after a thread is launched.
I generally see this done when a certain part of a function needs to be customized for certain cases. Allowing for the same function to take on multiple uses, this is demonstrated in the for_each function of C++, which goes through an iterable and applies a function to it. It really just allows for more reusable code.
On a related note, the C++ standard library uses a similar setup for it's container classes.
For example:
template < class T, class Container = deque<T> > class stack;
is the decleration for the stack class. As you can see, it takes in a configurable parameter for what it's underlying data structure is, this is similar to how a function pointer could be used.
EDIT: or the mentioned callbacks from other posters.

Good Practice for Templated Classes and Handling Unwanted Type Declarations

What is considered "good practice" in handling unwanted data types for templated classes?
Let's say we have a function in a templated class that does number multiplication, but the driver file for the class declares an instance of the class with Type string.
I've been given the argument that this is a "personal problem" for whoever's creating the driver file, and that all that needs to be done on your part is proper function prologues in the header/implementation files.
I'm wondering if there is a general practice used with templates regarding this issue. Do you check your Types in a class before handling them (I guess, to a certain extent that defeats the purpose of a template), or do you define behavior for specific types (though this also seems like a defeat of purpose)?
Or do you simply document your code correctly and let the programmer who uses your class take the precautions?
I'd generally use something like Boost/C++11 static_assert to assert the properties you want This will not only let you assure that it's numeric, but has things like is_signed and is_integer to assure more detail about the type, if you need/want to.

Reflexion Perfect Forwarding and the Visitor Pattern

http://codepad.org/etWqYnn3
I'm working on some form of a reflexion system for C++ despite the many who have warned against. What I'm looking at having is a set of interfaces IScope, IType, IMember, IMonikerClient and a wrapper class which contains the above say CReflexion. Ignoring all but the member which is the important part here is what I would like to do:
1) Instance the wrapper
2) Determine which type is to be used
3) Instance type
4) Overload the () and [] to access the contained member from outer(the wrapper) in code as easily as it is done when using a std::vector
I find that using 0x I can forward a method call with any type for a parameter. I can't however cast dynamically as cast doesn't take a variable(unless there are ways I am unaware of!)
I linked the rough idea above. I am currently using a switch statement to handle the varying interfaces. I would, and for obvious reasons, like to collapse this. I get type match errors in the switch cases as a cause of the call to the methods compiling against each case where only one of three work for any condition and compiler errors are thrown.
Could someone suggest anything to me here? That is aside from sticking to VARIANT :/
Thanks!
C++, even in "0x land", simply does not expose the kind of information you would need to create something like reflection.
I find that using 0x I can forward a method call with any type for a parameter.
You cannot forward a type as a parameter. You can forward the const-volatile qualifiers on a member, but that's all done in templates, at compile time. No runtime check ever is done when you're using things like forward.
Your template there for operator() is not going to compile unless T is convertable to int*, string*, and A** all at once. Think of templates as a simple find and replace algorithm that generates several functions for you -- the value of T gets replaced with the typename when the template is instantiated, and the function is compiled as normal.
Finally, you can only use dyanmic_cast to cast down the class hierarchy -- casting between the completely unrelated types A B and C isn't going to operate correctly.
You're better off taking the time to rethink your design such that it doesn't use reflection at all. It will probably be a better design anyway, considering even in language with reflection, reflection is most often used to paper over poor designs.

Why is RTTI necessary?

Why is RTTI (Runtime Type Information) necessary?
RTTI, Run-Time Type Information, introduces a [mild] form of reflection for C++.
It allows to know for example the type of a super class, hence allowing to handle an heterogeneous collection of objects which are all derived from the same base type. in ways that are specific to the individual super-classes. (Say you have an array of "Vehicle" objects and need to deal differently with the "Truck" objects found amid the array).
The question whether RTTI is necessary is however an open one. Story has it that Bjarne Stroustrup purposefully excluded this feature from the original C++ specification, by fear that it would be misused.
There are indeed opportunities to overuse/misuse reflection features, and this may have been even more of a factor when C++ was initially introduced because there wasn't such a OOP culture in the mainstream programmer community.
This said, with a more OOP savvy community, with the effective demonstration of all the good things reflection can do (eg. with languages such as Java or C#) and with the fancy design patterns in use nowadays, I strongly believe that RTTI and reflection features at large are very important even if sometimes misused.
I can think of exactly one case when it would be appropriate to use RTTI, and it doesn't even work.
It is fairly common for C-compatible APIs which perform callbacks to provide a user-defined void* to communicate a state structure back to the caller. When calling such an API from C++, it is quite common to pass the this pointer through said void* argument. From the callback, one might want to invoke virtual functions on the passed pointer.
In some cases when the callback parameters are insecure (such as LPARAM of a Windows message), it is obviously desirable to validate the pointer before using it for a virtual call, by checking the hidden vfptr. dynamic_cast is the natural way to do this, but results in undefined behavior exactly when the object is invalid (IIRC, it is undefined behavior if the pointer is to anything except an object with a virtual table). So RTTI is utterly useless for preventing a shatter attack in this way.
Feel free to present any other valid use cases for RTTI, cause I'm totally unconvinced.
EDIT: boost::any got mentioned. As far as boost::any is concerned, you can disable RTTI and use the following typeid implementation:
typedef const void* typeinfo_nonrtti;
template <typename T> typeinfo_nonrtti typeid_nonrtti();
template <typename T> class typeinfo_nonrtti_helper
{
friend typeinfo_nonrtti typeid_nonrtti<T>();
static char unique;
};
template <typename T> char typeinfo_nonrtti_helper<T>::unique;
template <typename T>
typeinfo_nonrtti typeid_nonrtti() { return &typeinfo_nonrtti_helper<T>::unique; }