1

Is it possible to iterate over a tuple with a lambda using boost::mpl::for_each? MPL documentation creates a separate class away from the call size which iterates over types given to for_each, can a lambda be used instead? Or can the separate class be written to take as an argument a lambda that would be applied with all types given to for_each? Something like this, except that incrementer should take a lambda (in constructor?) which defines the operations to do and which could be written at the call site of for_each:

#include "boost/mpl/for_each.hpp"
#include "tuple"

using namespace std;
using namespace boost::mpl;

template<class Tuple_T>
struct incrementer
{
    incrementer(Tuple_T& given) : tuple(given){}
    template<class T> void operator()(const T&)
    {
        // how to write this in main() instead?
        // [&](?){? += 1}?
        get<T>(this->tuple) += 1;
    }
    Tuple_T& tuple;
};

int main(){
    tuple<int, float, double> t{1, 2, 3};
    for_each<int, double>(incrementer<decltype(t)>(t));
    assert(get<0>(t) == 2);
    assert(get<1>(t) == 2);
    assert(get<2>(t) == 4);
    return 0;
}
dyp
  • 38,334
  • 13
  • 112
  • 177
user3493721
  • 185
  • 6
  • 3
    `#include "tuple"` o.O (Standard) Library headers should be included with `<>`, i.e. `#include ` – dyp Jun 18 '14 at 23:20
  • I think http://stackoverflow.com/questions/16387354/template-tuple-calling-a-function-on-each-element should achieve what you want, though it doesn't use boost::mpl::for_each. – Chris Hayden Jun 18 '14 at 23:50
  • 1
    > I think stackoverflow.com/questions/16387354... < That one uses indices/integers which won't work in this case. – user3493721 Jun 19 '14 at 13:49
  • http://coliru.stacked-crooked.com/a/a47a908c26467fd1 worked thanks, but c++1y is a bit too bleeding edge for me. Is there a c++11 way of doing something similar, perhaps with an external class taking a functor? – user3493721 Jun 19 '14 at 14:30
  • 1
    another c++14 one using tuples: http://stackoverflow.com/a/23235832. polymorphic lambdas seems the best tool you can get for the job. – oblitum Jun 20 '14 at 19:04
  • 2
    @user3493721 c++1y refers to c++14! c++1z refers to candidate c++17. – oblitum Jun 20 '14 at 19:20

0 Answers0