Overview of Boost.Hana capabilities
masterBoost.Hana is a C++14 library designed for metaprogramming, providing a 'standard library' for compile-time computations. Key features include:
- Heterogeneous Sequences: Sequences (like
hana::tuple) that can hold different types of objects, along with algorithms to manipulate them (e.g.,hana::transform,hana::reverse,hana::filter). - Compile-time Metadata: Even if a sequence contains runtime-only data (like
std::string), its properties likehana::lengthremainconstexpr. - Type-level Computations: Perform operations on types using the same syntax as normal C++ (e.g., using
hana::type_candhana::traits). - Compile-time Loops: Unroll loops at compile-time using
hana::int_c<N>.times([&]{ ... });. - Expression Validation: Easily check if an expression is valid using
hana::is_valid(a cleaner alternative to complex SFINAE tricks).
#include <boost/hana.hpp>
#include <cassert>
#include <string>
namespace hana = boost::hana;
using namespace hana::literals;
struct Fish { std::string name; };
struct Cat { std::string name; };
struct Dog { std::string name; };
int main() {
// Heterogeneous sequences and algorithms
auto animals = hana::make_tuple(Fish{"Nemo"}, Cat{"Garfield"}, Dog{"Snoopy"});
auto names = hana::transform(animals, [](auto a) {
return a.name;
});
assert(hana::reverse(names) == hana::make_tuple("Snoopy", "Garfield", "Nemo"));
// Compile-time length
static_assert(hana::length(animals) == 3u, "");
// Type-level computations
auto animal_types = hana::make_tuple(hana::type_c<Fish*>, hana::type_c<Cat&>, hana::type_c<Dog*>);
auto animal_ptrs = hana::filter(animal_types, [](auto a) {
return hana::traits::is_pointer(a);
});
static_assert(animal_ptrs == hana::make_tuple(hana::type_c<Fish*>, hana::type_c<Dog*>), "");
// Compile-time loop unrolling
std::string s;
hana::int_c<10>.times([&]{ s += "x"; });
// Expression validation
auto has_name = hana::is_valid([](auto&& x) -> decltype((void)x.name) { });
static_assert(has_name(animals[0_c]), "");
static_assert(!has_name(1), "");
}