2

Is it possible to check at compile time if T is a bitfield?

I'd like to use it in:

template <typename Allowed>
struct explicitly_constructible
{
   template <typename T, typename = std::enable_if_t<is_bitfield_v<T>>>
   constexpr operator T() const;
};

Example usage:

struct normal
{
   int foo;
};

struct with_bitfield
{
  int bar : 2;
};

normal n{explicitly_constructible<int>()}; // well-formed
with_bitfield m{explicitly_constructible<int>()}; // must be ill-formed

I am implementing a reflection library that provides for_each and get<Index> tuple-like functions for pod-like structs. Unfortunately, you can't use it on a struct with bitfields since it is UB to get an address of a bit-field. So I want to detect if a struct contains a bitfield to fire a compile-time error. Now I have some workaround - I compare struct size against evaluated, but I would like a simpler approach.

Sergey Kolesnik
  • 3,009
  • 1
  • 8
  • 28
  • @TedLyngmo I updated the question with an expected example usage. – Sergey Kolesnik May 19 '21 at 19:41
  • 5
    `T` can never be a bit-field. A bit-field member has its "type" converted in practically every context. It's impossible to obtain this "type" in a way that can be provided to a template. So this Q has strong marks of an XY problem. – StoryTeller - Unslander Monica May 19 '21 at 19:45
  • @SergeyKolesnik I see. So, [in this example](https://godbolt.org/z/YeocbbqfP) `ok` should be `ok`, but `nok` shouldn't? – Ted Lyngmo May 19 '21 at 19:46
  • @StoryTeller-UnslanderMonica *it is* an XY problem, but not as usual. I wrote in a comments what I am doing, and this seems to be very like the most desired solution. – Sergey Kolesnik May 19 '21 at 19:49
  • @TedLyngmo I didn't get it. I moved my comment to the answer. Basically `nok` with 2 bitfields `uint32_t : 16` can be initialized as `nok{uint32_t(), uint32_t()}`. That in sum will be 64 bits, but the real size of a `nok` struct is 32. That gives us a clue that `nok` contains bitfields and can't be used in a function. But you cannot use this trick if it contains only one bitfield... – Sergey Kolesnik May 19 '21 at 19:58
  • [this](https://stackoverflow.com/questions/20194009/size-of-a-bitfield-member/20194422#20194422) question has a compile time method for checking the bit size of a bitfield. Perhaps you could compare that size against the field type size? I'm not sure if this differs from what you said you are already doing. – Dean Johnson May 19 '21 at 20:05
  • @DeanJohnson I've seen that question. I can't use it because it requires to provide a struct member (in my case it is impossible). And I have C++11, so I can't do anything complex inside `constexpr` functions apart from returning. – Sergey Kolesnik May 19 '21 at 20:07
  • @StoryTeller-UnslanderMonica I suggest you to add an answer with an explanation you wrote in your comment. – Sergey Kolesnik May 19 '21 at 20:11

0 Answers0