Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ templated metaprogramming, checking if a struct has a field

So I recently discovered C++ does have reflections, it just happens no one, not even the C++ committee knew it yet until a Russian genius opened the door to an impossible to debug world of possibilities.

With that preface, let's look at this crime against humanity:

template <typename T, typename D = decltype(T().field)>
struct foo { bool b = true; };

template <typename T>
struct foo<T, void> { bool b = false; };

template <typename T>
constexpr bool HasField() { return foo<T>().b; }

That compiles and it works. Given any type whose members are not private, you can check whether or not the type defines a filed named field.

However, this forces you to write that pattern for every field you want to check for. It will work, but it will add a bunch of copy pasta everywhere and uglify the code (not that the code will be pretty if you copy that even once into it).

So, for sheer curiosity, I am trying to think what's the least disgusting way to make a generic POD field check.

One idea I had was this:

#define HAS_FIELD(field) \
    template <typename T, typename D = decltype(T().#field)> \
    struct foo_#field { bool b = true; }; \
    \
    template <typename T> \
    struct foo_#field<T, void> { bool b = false; }; \
    \
    template <typename T> \
    constexpr bool HasField#field() { return foo<T>().b; } 

This at least reduces the number of lines one has to write to just one macro invocation. But I am not satisfied, I am trying to see if we can use templates and macros to get a function that can be called anywhere without needing to preface stuff with macros.

i.e. We want to get to be able to do (or similar):

struct POD {/**/};
int main() { HasField(POD, FieldName); }

Note that currently it's almost possible:

struct POD {/**/};
HAS_FIELD(FieldName)
int main() { HasFieldFieldName<POD>(); }

Again the point isn;t whether this is a good idea, it's whether we can.

like image 722
Makogan Avatar asked Oct 23 '25 22:10

Makogan


2 Answers

You might wrap in a functor (as lambda):

// C++20
#define HasField(C, Field) \
    [](){ \
        return overloaded{[]<typename T>(int) -> decltype(std::declval<T>().Field, void(), std::true_type()) { return {}; }, \
                          []<typename T>(...) { return std::false_type{}; }}.operator()<C>(0); \
    }()

Demo

like image 93
Jarod42 Avatar answered Oct 25 '25 13:10

Jarod42


There is a generic technique presented in the book "C++ template, the complete guide" (thus this is not from me!), to test for member variable/function, class nested type. Here is an example:

namespace details
{
template <typename F, typename... Args, typename = decltype(std::declval<F>()(std::declval<Args &&>()...))>
auto
IsValidImpl(void *) -> std::true_type;

template <typename F, typename... Args>
auto
IsValidImpl(...) -> std::false_type;
} // namespace details

inline constexpr auto gk_isValid = [](auto f) {
  using InputType = decltype(f);
  return [](auto &&... args) { return decltype(details::IsValidImpl<InputType, decltype(args) &&...>(nullptr)){}; };
};

template <typename T>
struct TypeT
{
  using Type = T;
};

template <typename T>
constexpr auto gk_type = TypeT<T>{};

template <typename T>
T ValueT(TypeT<T>);

struct Foo {
    int bar;
};

struct Bar {
};

inline constexpr auto HasBar = gk_isValid([](auto x) -> decltype((void)ValueT(x).bar) {});

static_assert(HasBar(gk_type<Foo>), "foo has bar");
static_assert(!HasBar(gk_type<Bar>), "bar has no bar");

Example for checking nested type or operator:

constexpr auto hasSizeType = isValid([](auto x) -> typename decltype((void)valueT(x))::size_type {});
constexpr auto hasLess = isValid([](auto x, auto y) -> decltype(valueT(x) < valueT(y)) {});

Of course, you will need a kind of macro wrapping to make it more usable. But it is a first step to genericity...

like image 30
nop666 Avatar answered Oct 25 '25 13:10

nop666