On Thursday, 18 February 2016 00:58:07 UTC+2, JiiPee wrote:
> I have had this many times that I have some global (or static) non-class
> function which I want to get access to a certain class but not its
> private members. Just to illustrate (not a perfect example..):
I have only had such desire with "frozen" code that may not be
changed but that clearly lacks some vital functionality.
The 'private' isn't security. It just avoids accessing by accident
what you don't really want to access. In C++ everything is
accessible when you want to:
#include <iostream>
#include <string>
// frozen class
class Human
{
public:
Human(std::string name, int id)
: m_name(name)
, m_ID(id)
{}
std::string getName() const {return m_name;}
private:
std::string m_name;
int m_ID; /// humans id there are no way to access
};
// robbing template (from Johannes Schaub)
template<typename Tag, typename Tag::type M>
struct Rob
{
friend typename Tag::type get(Tag)
{
return M;
}
};
// preparations to rob Human::m_ID
struct Human_id
{
typedef int Human::*type;
friend type get(Human_id);
};
template struct Rob<Human_id, &Human::m_ID>;
// robbery in action:
bool checkHumansLegalStatus(const Human& human)
{
int id = human.*get(Human_id());
std::cout << "robbed: " << human.getName() << " " << id << '\n';
return id == 42;
}
int main()
{
Human jipee {"Jippee", 42};
return checkHumansLegalStatus(jipee);
}
> So I want only this function to get access to getID but on the other
> hand I do not want to make if a friend becouse I do not want it to get
> direct acces to the private data members (then it could also get access
> to other data members which it does not need). Protected kind of
> security would be pretty close what would do the job, but there is no
> "protected friend".
>
> What to do? I dont want it to be a friend, to expose ALL privates ...
> would be nice if C++ had a "conditional friend" .. so I could say which
> members it can get access to , like here.
I do not actually understand what you want or don't want. The issue may
be that your "class" is getters/setters and its *actual* logic of checking
its invariant is elsewhere outside. IOW design error.