Amit Limaye wrote:
i have a class with around 10-15 properties and i want to write
a single set get pair to access all these properties. Any suggestions.
Assuming that all members have a common type, you can use a bit of
template trickery:
#include <iostream>
class foo
{
public:
foo(): A(1), B(2), C(3) {}
enum member
{
memberA,
memberB,
memberC
};
template <member m> int get() const
{
return this->*members[m];
}
template <member m> void set(int v)
{
this->*members[m] = v;
}
private:
static int foo::*members[];
int A;
int B;
int C;
};
int foo::*foo::members[] = {
&foo::A,
&foo::B,
&foo::C
};
int main()
{
foo f;
std::cout << f.get<foo::memberA>() << " "
<< f.get<foo::memberB>() << " "
<< f.get<foo::memberC>() << "\n";
f.set<foo::memberB>(4);
std::cout << f.get<foo::memberA>() << " "
<< f.get<foo::memberB>() << " "
<< f.get<foo::memberC>() << "\n";
}
If the member types are different, things get really messy although
I think that with some template meta programming you can achieve
even this.
Since someone complained that this is ripping apart OOP: I don't
think it does and I can imagine reasons to do things this way.
However, personally, I would probably rather channel the various
member functions through one internal function.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.eai-systems.com> - Efficient Artificial Intelligence