Question

Problem: I need a functional object of A to recurse for data types of boost::tuple but do something else for all other data types of the incoming member t.

class A{
public:
    template<typename T>
    void operator()(T& t) const{
//      if (t == tuple){
//          recurse
//      } else{
//          doSomething
//      }
    }
};

class B{
    void init(){
        boost::tuple<int, float> a;
        boost::tuple< boost::tuple<int, std::string>, float > b;

        boost::fusion::for_each(a, A());
        boost::fusion::for_each(b, A());
    }
};

What I tried was setting up static functions for all possible incoming data types above the declaration of A but than I was not able to get back into the recursive function, because those statics did not know class A. My second approach was to implement static functions for all possible data types returning true for boost::tuple and false for any other (pretty much like in the example). But than I couldn't implement a for_each call, because (even though it was wrapped by the if case) my IDE says there was no matching function call (which is true for types of int, float and string).

Was it helpful?

Solution

If I understood your question correctly, you could just provide two overloads of the call operator, one which accepts instantiations of boost::tuple and would call boost::fusion::for_each() on that tuple, and another fallback one that would accept any kind of argument, and perform concrete operations on "leaf" types:

class A
{
public:
    template<typename T>
    void operator()(T& t) const
    {
        // Do something
    }

    template<typename... Ts>
    void operator ()(boost::tuple<Ts...>& t) const
    {
        // Recurse
        boost::fusion::for_each(t, A());
    }
};

In the above example I am using C++11's variadic templates, so you will need a C++11-compliant compiler for that to work (and don't forget to specify the flag -std=c++11 or -std=c++0x in the command line).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top