C ++ 14 Metaprogramming: automatically create a list of types at compile time / init

Using C ++ 14 and some combination of Curiously Recurring Template Pattern (CRTP) and possibly Boost.Hana (or boost::mplif you want), can I create a list of types at compile time (or static initialization time) without an explicit declaration?

As an example, I have something like this (see section ): Coliru

#include <iostream>
#include <boost/hana/tuple.hpp>
#include <boost/hana/for_each.hpp>

namespace
{
    struct D1 { static constexpr auto val = 10; };
    struct D2 { static constexpr auto val = 20; };
    struct D3 { static constexpr auto val = 30; };
}

int main()
{
    // How to avoid explicitly defining this?
    const auto list = boost::hana::tuple< D1, D2, D3 >{}; 

    // Do something with list
    boost::hana::for_each( list, []( auto t ) { std::cout << t.val << '\n'; } );
}

- D1, D2 D3 - list, , , , : " ". ( - factory, .)

- / init?

+4
3

"stateful". , , , ++ 14:

LX::push<void, void, void, void> ();
LX::set<0, class Hello> ();
LX::set<2, class World> ();
LX::pop ();

LX::value<> x; // type_list<class Hello, void, class World>

, ++ 11, . # 28.

, , .

, , MSVC. , Prove args . auto_register:

template<class T, class F>
int auto_register_factory()
{
    F::template apply<T>();
    return 0;
}

template<class T, class F>
struct auto_register
{
    static int static_register_;
    // This typedef ensures that the static member will be instantiated if
    // the class itself is instantiated
    typedef std::integral_constant<decltype(&static_register_), &static_register_> static_register_type_;
};

template<class T, class F>
int auto_register<T, F>::static_register_ = auto_register_factory<T, F>();

CRTP:

struct foo_register
{
    template<class T>
    static void apply()
    {
        // Do code when it encounters `T`
    }
};

template<class Derived>
struct fooable : auto_register<Derived, foo_register>
{};
+1

, . , ++ ( , ). , N4428 .

, .

+4

The only way I know to do this right now is with stateful metaprogramming, as described here . But it is difficult, difficult to implement, and the committee is trying to exclude it due to invalidity.

+1
source

Source: https://habr.com/ru/post/1668974/


All Articles