Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

unit testing - Mechanism to check if a C++ member is private

I am writing unit tests for undergraduate students and want to enforce certain members as public or private. I am aware of methods to actually test private members, e.g., #define private public or using a friend class, but have not seen anything that would allow me to check exactly if a member is private or not.

A brute force method would be trying a compile and parsing the output error, e.g., look for something like error: 'foo' is a private member of 'Bar', but I am hoping someone will have a better trick!

question from:https://stackoverflow.com/questions/64095320/mechanism-to-check-if-a-c-member-is-private

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...