Derived Functor with any return type and any parameters - c++

I have a class that uses functors as units of work. It accepts a reference to a functor in its Run() method. To allow this class to operate on any functor, all these functors must derive from my base functor class which looks like this:
class baseFunctor{
public:
virtual void operator()()=0;
virtual baseFunctor Clone()=0;
};
This works, however obviously it restricts these functors to having an operator method that returns void and accepts no parameters. I need to be able to accept a functor in my class that can take any type of parameters and return anything. Its apparently do-able but I can't seem to find a way to do it. I have considered using templates, multiple inheritance, but I keep getting thwarted by the fact that the class that needs to run this functor must be able to accept any type, so will accept the base class type, and so will not know the actual type of the functor.
Any suggestions of what avenue to look at would be appreciated.

How will the class that calls the functor know what parameters to provide and what to do with the return value, if any?

So, if I'm reading this right, you have a "Visitor pattern." It might be a good thing for you to look up.
Someone needs to know what type the functor is to give it arguments. Often with functors, the arguments are assigned to fields of the derived class, and operator() will operate on those fields. That is, the dumb method that calls the functor and doesn't know anything about it is given the closure (method plus arguments all in one class) by someone more knowledgeable.
If you do want generic functors that take multiple arguments in the operator(), templating will get you partway there, but you'll need one per arity.

I agree with Neil. Your main class has to know what parameters to pass and what return value to expect from these functors. Can you just type-cast your "functor" to an appropriate class that supports the function with the necessary arguments and return value?
class baseFunctor
{
};
class functor1x2: public baseFunctor
{
public:
virtual void* execute(void*, void*);
}
class MainClass
{
public:
void Execute(baseFunctor* ipFunctor)
{
functor1x2* lpFunctor1x2 = dynamic_cast<functor1x2*>(ipFunctor);
if(lpFunctor1x2)
{
lpFunctor1x2->execute(NULL, NULL);
}
}
}
I'm not sure what could be accomplished with this approach that couldn't more easily be accomplished with the Visitor pattern, as Drew noted.

If you are open to using the Boost library (www.boost.org), you might find Boot.Bind and Boost.Function of particular interest. I have used them in the past to achieve something very much along the lines of what you are discussing.
If you use Boost.Bind, you can perform currying on the functors to account for differences between the number of arguments the functor expects and the number of arguments the Run method expects (i.e., zero). The code that creates the functor would have to bind any arguments to specific values and thus create a zero-argument functor that can be passed to Run().
MV

Why'd you want to return the functor? Are you storing some state as well? Some more detail will be much appreciated since it is not very clear what exactly you want to do.
If you plan to use inheritance, do look up Covariant Return Types (and the Virtual Constructor idiom).
Now, for the meat of the problem: the problem is really not with passing in a functor but with functor application. You may want to take a look at boost::lambda and boost::parameter as well.

I think you want an ellipsis argument, like varargs for C++.

Perhaps std::tr1::function is interesting for you?

Related

Return different types from c++ functions

Ok, so I am struggling with the following:
I have a class (A), which holds a vector<B> (a vector for Qt) of some other classes (B). The class B has a property, let's say p and also has a name.
For one case, I would like to get a listing of the B objects that are to be found in class A which have the p property set, and for another case I would like to get a list of the names of the B objects that have the property set.
And most of all, I would like to have these two functions to be called the same :)
So, something like:
class A
{
public:
QVector<B*> B_s_with_p() { ... }
QStringList B_s_with_p() { ... }
};
but I don't want to have a helper parameter to overload the methods (yes, that would be easy), and the closest I have got is a method with a different name ... which works, but it's ugly. Templates don't seem to work either.
Is there a way using todays' C++ to achieve it?
A cheat would be to use a reference to QVector<B*> or QStringList as an argument instead of a return type. That way you can overload B_s_with_p as normal. I guess you don't consider that a valid option.
Only the signature is used to overload methods. That means the return type can't be use to overload.
You have to use different methods names or manage your return value with a parameter :
class A
{
public:
void B_s_with_p(QVector<B*>&);
void B_s_with_p(QStringList&);
};
B_s_with_p() could use a template type as parameter.
Why do you think that having two different names for two different sets of functionality is ugly? That's exactly what you should be doing to delineate the different return types here.
Another alternative is to have just the function that returns an object, and then create a names_of method that you pass the list of B objects and it returns the list of names.
Check your design .. Overloaded functions are one which have similar funcionality but differnt argument types .. So check why you want to
I would like to have these two functions to be called the same
refer to :What is the use/advantage of function overloading?
The benefit of overloading is consistency in the naming of functions which perform the same task, just with different parameters.

Sharing function between classes

I have three classes which each store their own array of double values. To populate the arrays I use a fairly complex function, lets say foo(), which takes in several parameters and calculates the appropriate values for the array.
Each of my three classes uses the same function with only minor adjustments (i.e. the input parameters vary slightly). Each of the classes is actually quite similar although they each perform separate logic when retrieving the values of the array.
So I am wondering how should I 'share' the function so that all classes can use it, without having to duplicate the code?
I was thinking of creating a base class which contained the function foo() and a virtual get() method. My three classes could then inherit this base class. Alternatively, I was also thinking perhaps a global function was the way to go? maybe putting the function into a namespace?
If the classes have nothing in common besides this foo() function, it is silly to put it in a base class; make it a free function instead. C++ is not Java.
Declaring of a function in base class sounds the most appropriate solution. Not sure if you need virtual "get" though, instead just declare the array in the base class and provide access method(s) for descendants.
More complex part is "the input parameters vary slightly". If parameters differ by type only then you may write a template function. If difference is more significant than the only solution I see is splitting main function into several logic blocks and using these blocks in descendant classes to perform final result.
If your classes are quite similar, you could create a template class with three different implementations that has the function foo<T>()
Implement that function in base class. If these classes are similar as you say, they should be derived from one base class anyway! If there are several functions like foo(), it might be reasonable in some cases to combine them into another class which is utilized by/with your classes.
If the underlying data of the class is the same (Array of doubles), considering using a single class and overloading the constructor, or just use 3 different functions:
void PopulateFromString(const string&)
void PopulateFromXml(...)
void PopulateFromInteger(...)
If the data or the behavior is different in each class type, then your solution of base class is good.
You can also define a function in the same namespace as your classes as utility function, if it has nothing to do with specific class behavior (Polymorphism). Bjarne StroupStroup recommends this method by the way.
For the purpose of this answer, I am assuming the classes you have are not common in any other outwards way; they may load the same data, but they are providing different interfaces.
There are two possible situations here, and you haven't told us which one it is. It could be more like
void foo(double* arr, size_t size) {
// Some specific code (that probably just does some preparation)
// Lots of generic code
// ...
// Some more specific code (cleanup?)
}
or something similar to
void foo(double* arr, size_t size) {
// generic_code();
// ...
// specific_code();
// generic_code();
// ...
}
In the first case, the generic code may very well be easy to put into a separate function, and then making a base class doesn't make much sense: you'll probably be inheriting from it privately, and you should prefer composition over private inheritance unless you have a good reason to. You could put the new function in its own class if it benefits from it, but it's not strictly necessary. Whether you put it in a namespace or not depends on how you're organising your code.
The second case is trickier, and in that case I would advise polymorphism. However, you don't seem to need runtime polymorphism for this, and so you could just as well do it compile-time. Using the fact that this is C++, you can use CRTP:
template<typename IMPL>
class MyBase {
void foo(double* arr, size_t size) {
// generic code
// ...
double importantResult = IMPL::DoALittleWork(/* args */);
// more generic code
// ...
}
};
class Derived : MyBase<Derived> {
static double DoALittleWork(/* params */) {
// My specific stuff
return result;
}
};
This gives you the benefit of code organisation and saves you some virtual functions. On the other hand, it does make it slightly less clear what functions need to be implemented (although the error messages are not that bad).
I would only go with the second route if making a new function (possibly within a new class) would clearly be uglier. If you're parsing different formats as Andrey says, then having a parser object (that would be polymorphic) passed in would be even nicer as it would allow you to mock things with less trouble, but you haven't given enough details to say for sure.

How to instantiate objects whose constructor requires parameters from a string holding the class name?

Is there a way to instantiate objects from a string holding their class name?
I got a problem basically the same with the above question. But I need to instantiate a class with some parameters. different class constructor name may require different number of variables and the type of each variable may differ either. And because the class contains constant variables so you could not new it with new T() and then set the parameter to the correct value. the "class name"-"constructor" map seems not suitable for my needs.
Any alternatives?
I'm going to preface this by saying, maybe C++ isn't the right language for whatever you're trying to accomplish. The more you try to control your program via external data, the closer you get to full on scripting. And there are lots of more powerful options when that is your goal.
That said, sure, it is possible, although not as easily. Two ways come immediately to mind. The first is to require all applicable types to have a constructor that accepts a std::string. This constructor will be responsible for its own parsing.
template<typename T> Base * createInstance(const std::string& s) { return new T(s); }
typedef std::map<std::string, Base*(*)(const std::string&)> map_type;
//...and similar changes as needed
If you don't want to change your type definitions, or this is otherwise unacceptable [perhaps your types already have such a constructor?], get rid of the templated createInstance method, and provide individual versions for each type you are interested in. This function does the parsing, and calls the appropriate constructor.
map["derivedA"] = createDerivedA;
map["derivedB"] = createDerivedB;
A third option might be possible using variadic templates [or boost-esque variadic-like templates] that would bring you back to the original simplicity.
template<typename T, typename... Args>
Base* create(std::string) {
//somehow pass the string to a generic function that packs the arguments into a tuple
//then somehow unpack that tuple and pass the bits to the constructor
}
map["derivedA"] = create<derivedA, int, double, std::string>;
However, I have no idea how to pull that off, or even if it is possible.
You could use a factory design patten. pass your string to the factory class and then let it decode your string choosing the correct version of the constructor and class to call. it would then pass back an instance of the correct class for the rest of your code to use.
Here's some info factory design pattern

Overriding methods by changing typedef in ancestor - possible?

I am trying to base my application on callbacks. The issue that bothers me the most is that I have to specify what arguments does the lambda function take. My base class that all others extend does specify two basic types. It looks like this:
class Callback
{
typedef function<void()> Function;
typedef vector< pair<string, vector<Function>> > CallbackContainer;
public:
void callback(string); // both types are used
Is it possible to change the arguments of the lambda function (the Function type) just by overriding the type in classes extending this one? Or does the code in the callback method use the original types? If so, can I force the usage of new types without copying and pasting the code? Just to fulfill the DRY.
Types are not virtual; you cannot "override" them in a derived class.
From my somewhat limited understanding of what you're trying to do, I think you should make Callback a template. Something like this:
template<typename ArgType>
class Callback
{
typedef function<void(ArgType)> Function;
typedef vector< pair<string, vector<Function>> > CallbackContainer;
public:
void callback(string); // both types are used
This works only for functions that take exactly one argument, of course. Making it more general in current-day C++ is far from trivial; in C++0x it gets a little bit easier with variadic templates.
Maybe you could have a look at Boost, though. There's a good chance that you can use something that is already in there, instead of rolling your own.

A more generic visitor pattern

I'm sorry if my question is so long and technical but I think it's so important other people will be interested about it
I was looking for a way to separate clearly some softwares internals from their representation in c++
I have a generic parameter class (to be later stored in a container) that can contain any kind of value with the the boost::any class
I have a base class (roughly) of this kind (of course there is more stuff)
class Parameter
{
public:
Parameter()
template typename<T> T GetValue() const { return any_cast<T>( _value ); }
template typename<T> void SetValue(const T& value) { _value = value; }
string GetValueAsString() const = 0;
void SetValueFromString(const string& str) const = 0;
private:
boost::any _value;
}
There are two levels of derived classes:
The first level defines the type and the conversion to/from string (for example ParameterInt or ParameterString)
The second level defines the behaviour and the real creators (for example deriving ParameterAnyInt and ParameterLimitedInt from ParameterInt or ParameterFilename from GenericString)
Depending on the real type I would like to add external function or classes that operates depending on the specific parameter type without adding virtual methods to the base class and without doing strange casts
For example I would like to create the proper gui controls depending on parameter types:
Widget* CreateWidget(const Parameter& p)
Of course I cannot understand real Parameter type from this unless I use RTTI or implement it my self (with enum and switch case), but this is not the right OOP design solution, you know.
The classical solution is the Visitor design pattern http://en.wikipedia.org/wiki/Visitor_pattern
The problem with this pattern is that I have to know in advance which derived types will be implemented, so (putting together what is written in wikipedia and my code) we'll have sort of:
struct Visitor
{
virtual void visit(ParameterLimitedInt& wheel) = 0;
virtual void visit(ParameterAnyInt& engine) = 0;
virtual void visit(ParameterFilename& body) = 0;
};
Is there any solution to obtain this behaviour in any other way without need to know in advance all the concrete types and without deriving the original visitor?
Edit: Dr. Pizza's solution seems the closest to what I was thinking, but the problem is still the same and the method is actually relying on dynamic_cast, that I was trying to avoid as a kind of (even if weak) RTTI method
Maybe it is better to think to some solution without even citing the visitor Pattern and clean our mind. The purpose is just having the function such:
Widget* CreateWidget(const Parameter& p)
behave differently for each "concrete" parameter without losing info on its type
For a generic implementation of Vistor, I'd suggest the Loki Visitor, part of the Loki library.
I've used this ("acyclic visitor") to good effect; it makes adding new classes to the hierarchy possible without changing existing ones, to some extent.
If I understand this correctly...
We had a object that could use different hardware options. To facilitate this we used a abstract interface of Device. Device had a bunch of functions that would be fired on certain events. The use would be the same but the various implementations of the Device would either have a fully-fleshed out functions or just return immediately. To make life even easier, the functions were void and threw exceptions on when something went wrong.
For completeness's sake:
it's of course completely possible to write an own implementation of a multimethod pointer table for your objects and calculate the method addresses manually at run time. There's a paper by Stroustrup on the topic of implementing multimethods (albeit in the compiler).
I wouldn't really advise anyone to do this. Getting the implementation to perform well is quite complicated and the syntax for using it will probably be very awkward and error-prone. If everything else fails, this might still be the way to go, though.
I am having trouble understanding your requirements. But Ill state - in my own words as it were - what I understand the situation to be:
You have abstract Parameter class, which is subclassed eventually to some concrete classes (eg: ParameterLimitedInt).
You have a seperate GUI system which will be passed these parameters in a generic fashion, but the catch is that it needs to present the GUI component specific to the concrete type of the parameter class.
The restrictions are that you dont want to do RTTID, and dont want to write code to handle every possible type of concrete parameter.
You are open to using the visitor pattern.
With those being your requirements, here is how I would handle such a situation:
I would implement the visitor pattern where the accept() returns a boolean value. The base Parameter class would implement a virtual accept() function and return false.
Concrete implementations of the Parameter class would then contain accept() functions which will call the visitor's visit(). They would return true.
The visitor class would make use of a templated visit() function so you would only override for the concrete Parameter types you care to support:
class Visitor
{
public:
template< class T > void visit( const T& param ) const
{
assert( false && "this parameter type not specialised in the visitor" );
}
void visit( const ParameterLimitedInt& ) const; // specialised implementations...
}
Thus if accept() returns false, you know the concrete type for the Parameter has not implemented the visitor pattern yet (in case there is additional logic you would prefer to handle on a case by case basis). If the assert() in the visitor pattern triggers, its because its not visiting a Parameter type which you've implemented a specialisation for.
One downside to all of this is that unsupported visits are only caught at runtime.