I have to wrap a getter function into a std::future object.
std::function<String (String)> -> std::function<std::future<String> (String)>
So simple question, what is the best / fastest way to do this?
Here are two options I came up with.
I have a function:
std::function<String (String)> getter;
Then wrap this using std::promise:
std::function<std::future<String> (String)> binding = [getter](String context) {
std::promise<String> p;
p.set_value(getter(contex));
return p.get_future();
};
Or using std::async:
std::function<std::future<String> (String)> binding = [getter](String context) {
return std::async(std::launch::deferred, getter, contex);
};
The right answer is to write your own make_ready_future (right out of std::experimantal). std::promise is about the only way I know of to produce a ready future: async produces non-ready futures.
This takes a value, and produces a future of that value, with some fancy stuff involving reference wrappers (which you can optionally skip).
A proposal to add it in C++1z exists, so by basing your own version off its interface, you can semi future-proof your code. Plus, as an audited design, it will suck less than your own.
Once you have it written:
template<class F>
auto futuristic_wrapper( F&& f ) {
return [f=std::forward<F>(f)](auto&&...args){
return make_ready_future( f( decltype(args)(args)... ) );
};
}
in C++11 you'd have to write a class to replace the lambda:
template<class F>
struct futurize {
F f;
template<class...Args>
operator()(Args&&...args)const->
delctype(make_ready_future(f(std::forward<Args>(args)...)))
{ return make_ready_future(f(std::forward<Args>(args)...)); }
};
template<class F>
auto futuristic_wrapper( F&& f )->
futurize< typename std::decay_t<F>::type >
{
return {std::forward<F>(f)};
}
which is annoying, but mostly a mechanical transformation.
This doesn't actually produce a std::function< future<R>(Args...) >, but it will return something convertible to that. No need to type erase if we don't need to after all.
You can put "your own version of to-be-standardized stuff" you steal from std::experimantal in a namespace like notstd. Always use it with notstd:: (never using namespace notstd;, and not using notstd::make_ready_future; as that risk behavior changes when the type is added to std) to be clear to later users that this is NOT the standard version of these objects.
Related
I need to iterate over folder either recursively or not (given the boolean parameter). I have discovered there is fs::recursive_directory_iterator() and also fs::directory_iterator(). In Java, I would expect them to implement the same interface or share the common ancestor so that I could substitute the needed one. But for some reason the two iterators do not share the common ancestor, forcing the to write the code like:
if (recursive_) {
path = recursive_iterator_->path();
recursive_iterator_++;
} else {
path = plain_iterator_->path();
plain_iterator_++;
}
I cannot believe this is how it is supposed to work. I also initially assumed there are some options to turn off recursion for recursive_directory_iterator but seems no any between std::filesystem::directory_options.
The value is not known at the compile time. I think it should be possible to use something like a closure or even subclass with virtual method but looks a bit like overkill.
Should I simply use conditionals switching between the two iterators as needed, or there are better approaches?
implement the same interface
They do. They are both InputIterators, that dereference to const std::filesystem::directory_entry&.
C++ avoids virtual by default.
You can use boost::any_range to type erase the recursiveness.
template <typename... Args>
auto make_directory_range(bool recursive, Args... args) {
return recursive
? boost::make_iterator_range(fs::recursive_directory_iterator(args...), fs::recursive_directory_iterator()) | boost::adaptors::type_erased()
: boost::make_iterator_range(fs::directory_iterator(args...), fs::directory_iterator());
}
using iterator_t = decltype(make_directory_range(true).begin());
auto range = make_directory_range(recursive_, args...);
iterator_t iterator = range.begin();
iterator_t end = range.end();
The usual way of dealing with a static polymorphism situation like this is to use a helper template:
template<class F,class ...AA>
void for_each_file(F f,bool rec,AA &&...aa) {
const auto g=[&](auto end) {
std::for_each(decltype(end)(std::forward<AA>(aa)...),
end,std::move(f));
};
if(rec) g(fs::recursive_directory_iterator());
else g(fs::directory_iterator());
}
std::size_t count(const fs::path &d,bool rec) {
std::size_t n=0;
for_each_file([&](fs::directory_entry) {++n;},rec,d);
return n;
}
This approach does have limitations: it makes it harder to break out of the “loop”, for example.
While building a small lambda-based metaprogramming library, I had the necessity of using recursion in a C++14 generic lambda, to implement a left-fold.
My own solution was passing the lambda itself as one of its parameters, like this:
template <typename TAcc, typename TF, typename... Ts>
constexpr auto fold_l_impl(TAcc acc, TF f, Ts... xs)
{
// Folding step.
auto step([=](auto self)
{
return [=](auto y_acc, auto y_x, auto... y_xs)
{
// Compute next folding step.
auto next(f(y_acc, y_x));
// Recurse if required.
return static_if(not_empty(y_xs...))
.then([=]
{
// Recursive case.
return self(self)(next, y_xs...);
})
.else_([=]
{
// Base case.
return next;
})();
};
});
// Start the left-fold.
return step(step)(acc, xs...);
}
step is the "main" lambda that starts off the recursion. It returns a function with the desired left-fold signature (accumulator, current item, remaining items...).
The function calls itself recursively by using self(self)(next, y_xs...).
I've recently come across this proposal that wants to add a Y Combinator to the Standard Library, and after reading it, it seems extremely similar to what I am doing here.
Unfortunately, the concept of the Y Combinator still doesn't "click" for me - I am missing something and I cannot visualize how to generalize what I did with the self parameter for any function, avoiding the step boilerplate.
I've read this excellent StackOverflow answer regarding the matter, but it still didn't "click" for me.
(From that answer) a recursive factorial is defined this way:
fact =
(recurs) =>
(x) =>
x == 0 ? 1 : x * recurs(x - 1);
The recurs parameter seems to have the same role as my self parameter. What I do not understand is how recurs is called without passing recurs into itself again.
I have to call self like this: self(self)(params...).
recurs, however, is called like recurs(params...).
Attempting to call self(params...) results in a compiler error informing me that self requires only a single parameter (which is the auto self lambda parameter).
What am I missing here? How could I rewrite my fold_l_impl lambda in such a way that its recursion could be generalized through the use of a Y Combinator?
Here is a y combinate where the lambda is passed a recurs that doesn't need to be passed recurs:
template<class F>
struct y_combinate_t {
F f;
template<class...Args>
decltype(auto) operator()(Args&&...args)const {
return f(*this, std::forward<Args>(args)...);
}
};
template<class F>
y_combinate_t<std::decay_t<F>> y_combinate( F&& f ) {
return {std::forward<F>(f)};
};
then you do:
return y_combinate(step)(acc, xs...);
and change
return self(self)(next, y_xs...);
to
return self(next, y_xs...);
the trick here is I used a non-lambda function object that has access to its own this, which I pass to f as its first parameter.
I would like to create a simple factory method with a simple C++ syntax:
void *createObject(const char *str,...)
{
if(!strcmp("X",str))
return new X(...);
}
I cannot figure out the syntax for this. I've been looking at template metaprogramming and use mpl::vectors, but I am not sure how to pass down this syntax. I want to really avoid using C va_lists if possible and go for a clean syntax like the one above.
This would be a better approach on C++11:
template< typename ...Args >
std::shared_ptr<void> createObject( std::string const& name, Args&& ...args )
{
if( name == "X" )
{
return try_make_shared< X >( std::forward< Args >( args )... );
}
/* other cases here*/
return nullptr;
}
template< typename T, typename ...Args >
typename std::enable_if<
std::is_constructible< T, Args >::value
, std::shared_ptr< T >
>::type try_make_shared( Args&&... args )
{
return std::make_shared< X >( std::forward< Args >( args )... );
}
template< typename T, typename ...Args >
typename std::enable_if<
!std::is_constructible< T, Args >::value
, std::shared_ptr< T >
>::type try_make_shared( Args&&... args )
{
throw std::invalid_argument( "The type is not constructible from the supplied arguments" );
return nullptr;
}
The differences with your code are
It uses a variadic template function instead of an ellipsis argument, thus the number and type of the parameters are still available at compile time (you don't loose type checking). Additionally you can call this function with non-POD types.
It returns a shared_ptr<void> instead of a plain void*. This allows you to control from within the factory how the object should be cleaned once all references to it are gone. The user doesn't need to know or care if he should call the standard delete, or maybe a deleteObject method from your factory.
Update: For those suggesting unique_ptr, you can read here about the possibilities that a shared_ptr brings to the table. A restricted factory that does only ever return pointers to new-ly allocated objects may and should use a unique_ptr.
In addition to the code on how to create objects using the nice C++11 variadic templates (as seen in K-ballo's answer), this answer shows how I would handle a set of classes in a project. This method is a big hack and only recommended if you know what you're doing, however, when adding new classes to your project, you only have to add them to a single file listing all your classes, so if the project gets huge, it helps to keep the overview.
Use this approach only, if you have to list your classes multiple times, for example if you also want to have a std::string className() function, for example, returning the name of a class without using C++ runtime type information. Every such function which requires to list all classes in your project can be implemented in a similar way than the following.
classes.h
/* For every class in your project which should be creatable through your
* factory, add a line here. */
CLASS(Foo)
CLASS(Bar)
CLASS(Baz)
factory.cpp
template< typename ...Args >
std::shared_ptr<void> createObject( std::string const& name, Args&& ...args )
{
// Define what code to insert for every class:
#define CLASS(T) \
else if(name == #T) \
return std::make_shared<T>(std::forward(args)...);
// List all cases:
if(0) /*do nothing*/; // <-- needed because the macro uses else if
#include "classes.h"
#undef CLASS
return nullptr;
}
If you can't use variadic templates, and don't want to use C-style varargs, your only option is to come up with some common representation for the arguments.
boost::shared_ptr<void> createObject(const char *str,
int argc, const char *argv[])
{
if(!strcmp("X",str))
return new X(argc, argv);
if(!strcmp("Y",str))
return make_Y(argc, argv);
}
as illustrated for Y, it may be sensible to split the argument handling out into a factory function instead of coupling your constructor to the option format. For example, you might want to switch to a property map or Boost program options.
The solution I ended up using was to create 0, N singletons with templated parameters. It is working pretty well with N = 8. A bit ugly, but only needs to be done once.
I've recently become enamored with the simplicity of Erlang's actor-based concurrency model, and am playing around with ideas for implementing some parts of it in C++. Along these lines, I also like the idea of implementing a finite state machine as a collection of functions representing states, where transitions are made by tail-calling from one function to the next.
I'd like to try something similar in C++. But a naive implementation of this is likely to run into the fact that tail calling in my compiler (GCC 4.1 with -O0) will eventually cause a stack overflow. So instead, what I'd like to do is have each state/function return a functor (the next state to enter), and have an underlying loop which just sequentially calls a functor, then calls the functor thus returned, then calls the functor thus returned, etc. Something like:
typedef ... context_t;
// A statefunctor is a functor which takes a context_t and
// returns a statefunctor
//
// FIXME: of course, this typedef won't compile.
typedef boost::function<statefunctor (context_t& )> statefunctor;
// NULL boost::function<> represents the exit condition.
static const statefunctor EXIT_FSM;
// primary loop which runs the FSM
void run_fsm(context_t& ctx, statefunctor initial_state)
{
while (initial_state)
{
initial_state=initial_state(boost::ref(ctx));
}
}
// states 'foo', 'bar', and 'baz';
statefunctor foo(context_t& ctx);
statefunctor bar(context_t& ctx, int inval);
statefunctor baz(context_t& ctx);
// State 'foo'
statefunctor foo(context_t& ctx)
{
// act somehow on the external context
int magic_number_1=ctx.get_magic_number();
int magic_number_2=ctx.get_magic_number();
// Always transition to 'bar'
return boost::bind(&bar, _1, magic_number_1-magic_number_2);
}
// State 'bar'
statefunctor bar(context_t& ctx, int inval)
{
inval+=ctx.get_magic_number(); // Act on external context somehow
// transition to foo or baz
if (inval>0) { return &foo; }
else { return &baz; }
}
// State 'baz'
statefunctor baz(context_t& ctx)
{
// Transition to foo or exit
if (ctx.get_magic_number()==5) {return EXIT_FSM;}
else {return &foo;}
}
int main()
{
context_t ctx;
// start the state machine in state 'foo'
run_fsm(ctx, &foo);
}
So, my question is, how do I define statefunctor? In particular, I want it to be capable of holding arbitrary functors (like boost::bind(...) might create), and not just function pointers.
NOTE: I'm using boost::bind, boost::function, boost::ref instead of their std:: counterparts because I'm stuck using GCC 4.1, which has no support for C++11. Solutions valid in C++03 are appreciated ;-).
You can't directly do this through a typedef, but you can wrap the boost::function in a struct / class (thanks to #R. Martinho Fernandes for making me have this insight):
#include <boost/function.hpp>
typedef int context_t;
struct statefunctor
: boost::function<statefunctor(context_t&)>
{
typedef boost::function<statefunctor(context_t&)> base_type;
statefunctor() : base_type(){}
template<class F>
statefunctor(F f) : base_type(f){}
};
Live example.
This is impossibru. The type would be infinite, and the problem is identical to the one you would encounter defining a function pointer that returns itself. The only way to do this is to manually write your own function object with an operator(), this can return *this, and chain() calls. You can also use operator chaining in other ways, like you can see in std::cout.
You cannot. The problem is that the definition of the returned type would have to be recursive and that is not possible.
I have an application which has a lot of functions which go through all the elements of a menu toolbar.
The code looks like something like this:
subMenuDefaultMenuShortcuts( ui->fileMenu );
subMenuDefaultMenuShortcuts(ui->editMenu);
subMenuDefaultMenuShortcuts(ui->windowMenu);
subMenuDefaultMenuShortcuts(ui->helpMenu);
subMenuUpdateLabels(ui->fileMenu,hierarchy);
subMenuUpdateLabels(ui->editMenu,hierarchy);
subMenuUpdateLabels(ui->windowMenu,hierarchy);
subMenuUpdateLabels(ui->helpMenu,hierarchy);
It is possible i will change this implementation, or menus could have sub menus. Thus search and replacing code, is not only ugly, but also hardly readable and error prone.
ideally i whould want something like this:
OnAllMenus(functionName,params ...)
so my code whould look like:
OnAllMenus(subMenuUpdateLabels)
OnAllMenus(subMenuUpdateLabels,hierarchy)
OnAllMenus(someFunction,hierarchy,argument1,argument2)
I wanted to use macro, but their usage is not recommended.
Howerver using inline functions with function pointers seems to lead to some hardly readable code. (And i did not see any example with function pointers expecting variable number of arguments with a function).
Is there any better / cleaner way to do it without addind some overly complex unmaintanable code.
template<typename FuncPointer, typename ... Args>
void for_all_menus(FuncPointer func, Args ... args)
{
f(ui->foo,std::forward<Args>(args)...);
f(ui->bar,std::forward<Args>(args)...);
// etc
}
// use
for_all_menus(&subMenuLabel, hierarchy);
Pmr's answer, but variadic templates to stop the stupid boost::binds that will be scattered everywhere.
You can use boost::function and boost::bind.
template<typename Func>
void for_all_menus(Func f) {
f(ui->foo);
f(ui->bar);
// etc
}
// use
for_all_menus(boost::bind(subMenuLabel, _1, hierarchy));
// with variadic templates
template<typename Func, typename Args...>
struct for_all_menus {
Func f;
void operator()(Args&&... args) {
// umh, I always mess up the syntax
// you might want to double check this
f(ui->foo, std::forward<Args>(args)...);
}
};
template<typename F>
for_all_menus<F> make_for_all_menus(F f) { return for_all_menus<F>{f}; }
// use
auto f = make_for_all_menus(subMenuLabel);
f(hierarchy);
If you need something more dynamic simply replace the function
template with a function that takes a boost::function. Of course you
can also use the C++11 equivalents and lambdas.
If you want to get the list of menus into one place and use that list
in different places, I'd recommend Boost.Preprocessor. But you might
want to think twice before resorting to it.