Use boost::function as function argument? - c++

I want to call a function foo and let it behave differently.
(I'm adopting Strategy or Command pattern. They look similar to me.)
My overall plan is as follows..
First, define foo to take boost::function type
foo(boost::function<someType> execFunction)
{
// do something
execFunction(args);
// do something
}
Then, I give foo() different functions(as argument) depending on what I want.
Would this work? or Would you advise against it?
Any comments are welcome.
edit
Minor related question is,
sometimes execFunction needs 1 argument, and other times it needs 2 arguments.
I could use boost::function for both cases and just ignore the 2nd argument when not needed.
Is there a cleaner way to do this?

This works very well. But sometimes it is preferable to work with a
functor so your callers are free to choose what is best for them and to prevent the smalll overhead that comes with a boost::function:
template<typename Func>
void foo(Func f) {
f(myArgs);
}
You can also add an overload for the specific boost::function to take the object by reference.
template<>
void foo(const boost::function<void (expectedtypes)>& f) {
f(myArgs);
}
And possibly have that overloaded for constness as well.
For the case of accepting boost::function objects of different arity, I'd use overloading. If you go that route, avoid the templated version as you are going to run into trouble as soon as your users try to work with functors (as opposed to boost::function with different arity). This trouble is resolvable, but can get messy. You would need to dispatch the call to something that detects the arity of the funtor and executes the proper call. But as you said that templates are your weak-point, this isn't really recommended.

That is a common pattern, and will work. I have used that in the past and will most probably use it in the future. I try to use it only in some specific use cases, as it reduces drastically coupling, and while that is good in general, it makes it harder to follow the flow of control from the code (i.e. if you abuse it, it will be really hard to find what your program is meant to do other than running it in the debugger). But for specific tasks it is fine.
If you do not need to store the function<> for later use, or any runtime polymorphic behavior on the callee side, you can also consider using a function template, so that callers don't need to convert to function<> before executing your function.

Related

Why doesn't QTCreator warn me if an emplace_back is completely wrong?

Let's say I have this vector of pairs of numbers:
std::vector<std::pair<ulong, ulong>> uniquePairs;
If I do:
uniquePairs.emplace_back("literal garbage data");
It doesn't yell at me. Shouldn't something be screaming at me that this code is horribly, completely wrong? There are no warnings from the linter at all.
Of course, it fails when I go to actually compile with GCC.
If I do:
uniquePairs.emplace_back("literal garbage data");
It doesn't yell at me.
Because it doesn't check for correctness of (execution of) such statement.
The real question, then, is - why it doesn't do so?
The answer is: because that's usually a lot of work. Let's examine this very case:
uniquePairs.emplace_back("literal garbage data");
attempts to call template< class... Args > reference emplace_back( Args&&... args ), where Args is a parameter pack consisting of one type - const char[21]. Keep in mind that "c-string literals" have distinct types for every length of the literal. This is problem #1.
Problem #1:
Instantiating emplace_backs for all the types you're calling with it. It's not that much work, but it may add up afterwards.
Successful instantiation of said function template results in (by definition of the function), perfect forwarding, i.e., problem #2.
Problem #2:
Calling (instantiating) std::forward. This is just repeating problem #1, but in another scope. Not great, not terrible.
Problem #3:
After we already instantiated (in the background, without full intent of compilation) some function templates, we now need to check if perfectly forwarded arguments for emplace_back can construct a value_type of your std::vector.
Your value_type is std::pair<ulong, ulong>. Obviously, const char[21] cannot do that. Your IDE can now scream at you.
This is a pretty trivial case, but notice how much work had to be done at the first place. Now imagine that you are perfect forwarding something else. More arguments. More calls. More background instantiations.
Background code sanitisers should not interrupt your work. They also should (hopefully) give you reliable hints in a reasonable time fashion. This very feature may be quite trivial (your case) or very complicated. The simples answer is just to not attempt to accomplish such tasks.
Bonus:
Why, then, if you push_back("literal garbage data"), the IDE usually yells at you?
Because push_back's signature takes either const T& or T&& for std::vector<T>. It's pretty trivial to see that const char[21] is not a std::pair<ulong, ulong> (neither is convertible to one). No instantiations needed (provided that the instantiation of your vector was already done at the background. If not, add another problem to both cases). Not a lof of work. Easy to compute, easy to warn about.

How does c++11 resolve constexpr into assembly?

The basic question:
Edit: v-The question-v
class foo {
public:
constexpr foo() { }
constexpr int operator()(const int& i) { return int(i); }
}
Performance is a non-trivial issue. How does the compiler actually compile the above? I know how I want it to be resolved, but how does the specification actually specify it will be resolved?
1) Seeing the type int has a constexpr constructor, create a int object and compile the string of bytes that make the type from memory into the code directly?
2) Replace any calls to the overload with a call to the 'int's constructor that for some unknown reason int doesn't have constexpr constructors? (Inlining the call.)
3) Create a function, call the function, and have that function call 'int's consctructor?
Why I want to know, and how I plan to use the knowledge
edit:v-Background only-v
The real library I'm working with uses template arguments to decide how a given type should be passed between functions. That is, by reference or by value because the exact size of the type is unknown. It will be a user's responsibility to work within the limits I give them, but I want these limits to be as light and user friendly as I can sanely make them.
I expect a simple single byte character to be passed around in which case it should be passed by value. I do not bar 300mega-byte behemoth that does several minuets of recalculation every time a copy constructor is invoked. In which case passing by reference makes more sense. I have only a list of requirements that a type must comply with, not set cap on what a type can or can not do.
Why I want to know the answer to my question is so I can in good faith make a function object that accepts this unknown template, and then makes a decision how, when, or even how much of a object should be copied. Via a virtual member function and a pointer allocated with new is so required. If the compiler resolves constexpr badly I need to know so I can abandon this line of thought and/or find a new one. Again, It will be a user's responsibility to work within the limits I give them, but I want these limits to be as light and user friendly as I can sanely make them.
Edit: Thank you for your answers. The only real question was the second sentence. It has now been answered. Everything else If more background is required, Allow me to restate the above:
I have a template with four argument. The goal of the template is a routing protocol. Be that TCP/IP -unlikely- or node to node within a game -possible. The first two are for data storage. They have no requirement beyond a list of operators for each. The last two define how the data is passed within the template. By default this is by reference. For performance and freedom of use, these can be changed define to pass information by value at a user's request.
Each is expect to be a single byte long. They could in the case of metric for a EIGRP or OSFP like protocol the second template argument could be the compound of a dozen or more different variable. Each taking a non-trival time to copy or recompute.
For ease of use I investigate the use a function object that accepts the third and fourth template to handle special cases and polymorphic classes that would fail to function or copy correctly. The goal to not force a user to rebuild their objects from scratch. This would require planning for virtual function to preform deep copies, or any number of other unknown oddites. The usefulness of the function object depends on how sanely a compiler can be depended on not generate a cascade of function calls.
More helpful I hope?
The C++11 standard doesn't say anything about how constexpr will be compiled down to machine instructions. The standard just says that expressions that are constexpr may be used in contexts where a compile time constant value is required. How any particular compiler chooses to translate that to executable code is an implementation issue.
Now in general, with optimizations turned on you can expect a reasonable compiler to not execute any code at runtime for many uses of constexpr but there aren't really any guarantees. I'm not really clear on what exactly you're asking about in your example so it's hard to give any specifics about your use case.
constexpr expressions are not special. For all intents and purposes, they're basically const unless the context they're used in is constexpr and all variables/functions are also constexpr. It is implementation defined how the compiler chooses to handle this. The Standard never deals with implementation details because it speaks in abstract terms.

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.

boost::bind accessors?

Suppose I have the following code:
int f(int, int);
int main()
{
SomeFunc(boost::bind(f, 1, 2));
}
From the SomeFunc() function, is it possible to access the arguments held by the bound type? Something like this (pseudo code):
// Obvious syntax issues...
void SomeFunc(boost::bind& functor)
{
if(functor.function == &f)
{
if(functor.argument1 == 1)
DoSomething();
}
}
Can I pull this information out of the boost::bind type?
boost::bind is a templated function, not a type. The real type returned by that function is some kind of functor of an unspecified type. As a matter of fact, it probably returns many different unspecified types depending on what the arguments to the boost::bind function are.
As the type is unspecified and the library only states that is CopyConstructible, that implements operator() with the appropriate number and type of arguments (one for each placeholder, types deduced from the bound method/function) and that it offers an inner type result_type that is the same as the return type of that operator().
The interface of those unspecified classes is, well, unspecified. It will probably not offer accessors to the arguments, and even if it does, and you get inside knowledge from studying the internals of the library, you risk having your code break with upgrades to the library (the implementor is free to change the type and all the interface that is not publicly documented).
The whole library is built around the fact that you do not really care about what the arguments are or even if any argument is defined or only placeholders are used, you only care that the resulting object will be callable with a given interface.
So no, you cannot.
The real question is why would you want to do that?
I suspect you can't but the fact that you are trying is a bit worrying.
No, you cannot do that with boost::bind.
boost::bind just generates a sort of functor object where all details are hidden. Than you construct boost::function or boost::signal with it and the only thing you can do: execute. You even cannot compare boost::function objects.
Anyway, it is not clear that the problem you are solving. Such approach looks awkward to me. Are you sure you really need that?

Functor class doing work in constructor

I'm using C++ templates to pass in Strategy functors to change my function's behavior. It works fine. The functor I pass is a stateless class with no storage and it just overloads the () operator in the classic functor way.
template <typename Operation> int foo(int a)
{
int b=Operation()(a);
/* use b here, etc */
}
I do this often, and it works well, and often I'm making templates with 6 or 7 templated functors passed in!
However I worry both about code elegance and also efficiency. The functor is stateless so I assume the Operation() constructor is free and the evaluation of the functor is just as efficient as an inlined function, but like all C++ programmers I always have some nagging doubt.
My second question is whether I could use an alternate functor approach.. one that does not override the () operator, but does everything in the constructor as a side effect!
Something like:
struct Operation {
Operation(int a, int &b) { b=a*a; }
};
template <typename Operation> int foo(int a)
{
int b;
Operation(a,b);
/* use b here, etc */
}
I've never seen anyone use a constructor as the "work" of a functor, but it seems like it should work. Is there any advantage? Any disadvantage? I do like the removal of the strange doubled parenthesis "Operator()(a)" , but that's likely just aesthetic.
Any disadvantage?
Ctors do not return any useful value -- cannot be used in chained calls (e.g. foo(bar()).
They can throw.
Design point of view -- ctors are object creation functions, not really meant to be workhorses.
Compilers actually inline the empty constructor of Operation (at least gcc in similar situations does, except when you turned off optimization)
The disadvantage of doing everything in the constructor is that you cannot create a functor with some internal state this way - eg. functor for counting the number of elements satisfying a predicate. Also, using a method of a real object as a functor allows you to store the instance of it for later execution, something you cannot do with your constructor approach.
From a performance pov the code demonstrated with get completely optimized with both VC and GCC. However, a better strategy often is to take the functor as a parameter, that way you get a lot more flexibility and identical performance characteristics.
I'd recommend defining functor that work with the STL-containers, i.e. they should implement operator(). (Following the API of the language you're using is always a good idea.)
That allow your algorithms to be very generic (pass in functions, functors, stl-bind, boost::function, boost::bind, boost::lambda, ...) which is what one usually wants.
This way, you don't need to specify the functor type as a template parameter, just construct an instance and pass it in:
my_algorithm(foo, bar, MyOperation())
There does not seem any point in implementing the constructor in another class.
All you are doing is breaking encapsulation and setting up your class for abuse.
The constructor is supposed to initialize the object into a good state as defined by the class. You are allowing another object to initialize your class. What guarantees do you have that this template class knows how to initialize your class correctly? A user of your class can provide any object that could mess with the internal state of your object in ways not intended.
The class should be self contained and initialize itself to a good state. What you seem to be doing is playing with templates just to see what they can do.