How to static_assert each data member of a C++ lambda?

88 Views Asked by At

How can one call static_assert for each data member of any given C++ lambda?

What I'm trying to do is roll my own memcpy-able std::function and have realized that any lambdas must have trivially copyable data members. I'd like to put some assertions in place for this.

Example:

template<typename T> struct has_trivial_copy {enum {value = false};};
template<> struct has_trivial_copy<int> {enum {value = true};};

int main() {
    int i = 0;
    std::string str;

    auto lambda1 = [i] {
        // static_assert(has_trivial_copy<each data member...>::value); // okay
    };

    auto lambda2 = [i, str] {
        // static_assert(has_trivial_copy<each data member...>::value); // fail
    };
}
1

There are 1 best solutions below

2
Nathanael Weiss On BEST ANSWER

While it's not possible to call static_assert for every member of a lambda, it is possible to use std::is_trivially_copyable on any given lambda to assert that it is trivially copyable.

I've added the following static_assert to my custom std::function and it works nicely to show me all the places where I'm using non-trivially copyable data members in lambdas:

template <typename Functor, typename ReturnType, typename... Args>
struct FunctorHolder
{
    FunctorHolder (Functor func) : f (func)
    {
        static_assert(std::is_trivially_copyable<Functor>::value);
    }

    Functor f;
};