Mechanism to check if a C++ member is private

If you want to assert that a type Bar doesn’t have a public member named foo, you can write the following test:

template<typename T>
constexpr auto has_public_foo(T const &t) -> decltype(t.foo, true) 
{
    return true;
}

constexpr auto has_public_foo(...) 
{
    return false;
}

static_assert(not has_public_foo(Bar{}), "Public members are bad practice");

Here’s a demo.

Leave a Comment

tech