dimanche 16 août 2020

Fancy hack to get reflection breaking locally but not in online compiler

Some smart guy: get the number of fields in a class https://www.youtube.com/watch?v=abdeAew3gmQ

Figured how to use template meta programming to get some basic reflection going.

Well, I am trying to integrate that with my code and it's causing issues.

In an online compiler this works:

#include <iostream>
#include <tuple>
#include <iostream>
#include <array>
#include <utility>

using namespace std;

template <std::size_t I>
struct ubiq_constructor
{
    template <class Type>
    constexpr operator Type&() const noexcept;
};

template <class T, std::size_t I0, std::size_t... I>
constexpr auto detect_fields_count(std::size_t& out, std::index_sequence<I0, I...>)
    -> decltype( T{ ubiq_constructor<I0>{}, ubiq_constructor<I>{}... } )
{ out = sizeof...(I) + 1; }

template <class T, std::size_t... I>
constexpr void detect_fields_count(std::size_t& out, std::index_sequence<I...>) {
    detect_fields_count<T>(out, std::make_index_sequence<sizeof...(I) - 1>{});
}

struct POD {
    int f1;
    float f2;
    char h;
    char w;
};


int main()
{
    std::size_t size;
    detect_fields_count<POD>(size, std::make_index_sequence<sizeof(POD)>());
    cout << "size:" << size << endl;

    return 0;
}

Output: size:4

However when I put it in a much larger project local project that is compiled with gcc I am geting what seems UB. My program terminates early, sometimes hitting a segfault, but sometimes not even that happens, my code just stops and not even gdb knows why.

All of the tests I have pass, the code compiles with only one warning (which is part of the template) and if I comment out any calls to it, the code works normally, i.e

int example()
{
    cout << "AAAAAAAAAAAAAAAA: " << endl;
    std::size_t size = 0;
    detect_fields_count<POD>(size, std::make_index_sequence<sizeof(POD)>());
    cout << "size: " << size << endl;
    return 0;
}

In that example if I comment out detect_fields_count my code works, otherwise, I might get a segfault, I might double print "AAAAAAAAA" and then get a segfault...

I don't understand what's happening the templated code should not be breaking things as far as I can see, but it somehow is, even when I comment out all calls to other functions in my code. I don't even know where to begin debugging this.





Aucun commentaire:

Enregistrer un commentaire