Re: template friend class
Hi!
Kira Yamato schrieb:
Well, I'm trying to write a template to implement some inner classes.
To be more specific, I have the following template
template<class C, typename M, M (C::*get)() const, void (C::*set)(const
M &)>
class member_accessor : private noncopyable
{
public:
member_accessor(C &c) : c(c) {}
operator M() const { return (c.*get)(); }
member_accessor &operator=(const M &n) { (c.*set)(n); return
*this; }
private:
C &c;
};
Looks like you are trying to implement properties by the backdoor.
But there are more semantics like += which are still not working unless
you pass a bunch of functions or emulate the operators by using get/set
like C# does. I would not recommend the latter because it pretenda a
feature which is not there in effect.
This template allows me to write the following:
class A
{
public:
A() : x(*this) {}
int get_x() const;
void set_x(const int &y);
I would have expected get_x and set_x to be non-public in this case, but
anyway.
member_accessor<A, int, &A::get_x, &A::set_x> x;
};
However, I want to hide the constructor of 'member_accessor' so that
only the container class C can initiate object of type
member_accessor<C, ...>.
You can make the constructor protected and derive from member_accessor
within a private class A::my_accessor. This can be a friend of A in the
required specializations.
But I see no reason why the constructor should be private. From the
proxy's point of view this is a public function.
However, I do not see the significant benefit of the whole effort. You
save two braces per access to x. That's it. The "get_" and "set_"
prefixes are not required.
Marcel