c++c++14template-meta-programmingboost-hana

Understanding Boost.Hana Quick start


I'm going through Boost.Hana's User Manual to learn more about template meta programming and functional programming in C++.

As regards the Real world example, I still miss a few bits, all concentrated in the definition of the following function:

template<typename Any, typename Default, typename Case, typename ...Rest>
auto process(Any a, std::type_index const& t, Default default_, Case& case_, Rest ...rest) {
    using T = typename decltype(+hana::first(case_))::type;
    return typeid(T) == t ? hana::second(case_)(*boost::unsafe_any_cast<T>(&a))
                          : process(a, t, default_, rest...);
};

Here are my doubts and questions:


Solution

  • I'll try to answer the question about that using line:

    You need some machinery to extract that original type that was passed to hana::make_pair - if you were building something to solve only your particular problem you would make it simpler, but they need to make the library so generic that it will solve everybody's problems and that adds complexity.

    As for that second return line:

    The whole premise of the example is that switch_ is passed a boost::any and it calls the right lambda with the contents of the boost::any.

    hana::second(case_) is one of the lambdas originally given to switch_ so if you use hana::second(case_)(a) then a boost::any gets passed to your lambda but the code inside the lambda isn't expecting a boost::any so the error message says std::to_string doesn't accept a boost::any.

    You could actually use hana::second(case_)(a) and then cast the boost::any parameter back to the original type inside the lambda. That would actually work fine, but I think that is something switch_ should be doing for you so that the lambda gets the type you expect.

    It's just unfortunate that boost::any requires such a terrible cast syntax.