lundi 1 avril 2019

C++: Use a reflection to loop over elements in a struct?

I have the following codes which work fine. Basically it is going over all pointers in my_struct, apply my_fun on each pointer and assign the corresponding output to my_array.

   enum class MyEnum {
       head = 0,
       tail = 1,
       left_head = 2,
       left_tail = 3,
       right_head = 4,
       right_tail = 5,
   };

    auto head_ptr = my_struct.head_;
    auto tail_ptr = my_struct.tail_;
    auto left_head_ptr = my_struct.left_head_;
    auto left_tail_ptr = my_struct.left_tail_;
    auto right_head_ptr = my_struct.right_head_;
    auto right_tail_ptr = my_struct.right_tail_;

    if (head_ptr) {
        my_array[static_cast<size_t>(MyEnum::head)] = my_fun(head_ptr);
    }

    if (tail_ptr) {
        my_array[static_cast<size_t>(MyEnum::tail)] = my_fun(tail_ptr);
    }

    if (left_head_ptr) {
        my_array[static_cast<size_t>(MyEnum::left_head)] = my_fun(left_head_ptr);
    }

    if (left_tail_ptr) {
        my_array[static_cast<size_t>(MyEnum::left_tail)] = my_fun(left_tail_ptr);
    }

    if (right_head_ptr) {
        my_array[static_cast<size_t>(MyEnum::right_head)] = my_fun(right_head_ptr);
    }

    if (right_tail_ptr) {
        my_array[static_cast<size_t>(MyEnum::right_tail)] = my_fun(right_tail_ptr);
    }

I am wondering is there a more elegant way to do this? Maybe something like the reflection in Java? Thanks a lot!





Aucun commentaire:

Enregistrer un commentaire