Ok, maybe my problem is a little contrieved.
I am trying to find an elegant solution in order to reduce the following boilerplate code each time I want to modify a part of an object which is only accessible through a const Getter and a non const Setter.
Content c = container.GetContent();
c.SetX(3);
container.SetContent(c);
I know I could have a non const getter, but I'd like to stick with it for the time being.
So, I tried to use lambdas and I have currently the following implementation :
#include <iostream>
class Content
{
public:
Content(int x) :mX(x) {}
const int GetX() const
{
return mX;
}
void SetX(const int &x)
{
mX = x;
}
private:
int mX;
};
//for clarity ContentFunctionChanger is a typedef for any function of type : void f(Content &)
typedef void (*ContentFunctionChanger)(Content &);
class Container
{
public:
Container(const Content &c) :mContent(c) {}
const Content & GetContent() const
{
return mContent;
}
void SetContent(const Content &c)
{
mContent = c;
}
void ChangeContent(ContentFunctionChanger &function)
{
(*function)(mContent);
}
private:
Content mContent;
};
int main()
{
Content content(1);
Container container(content);
std::cout << "x=" << container.GetContent().GetX() << std::endl;
{
//Classic method using Get() then Set()
Content c = container.GetContent();
c.SetX(3);
container.SetContent(c);
std::cout << "x=" << container.GetContent().GetX() << std::endl;
}
{
//Method 1 : with a named lambda function whose type is written at the declaration
//It works, but it is not concise
ContentFunctionChanger func = [] (Content & c) { c.SetX(5); };
container.ChangeContent(func);
std::cout << "x=" << container.GetContent().GetX() << std::endl;
}
/*
{
//Method 2 : with a named lambda function whose type is not written (using auto)
//It will not compile...
auto func = [] (Content & c) { c.SetX(7); };
container.ChangeContent(func);
std::cout << "x=" << container.GetContent().GetX() << std::endl;
}
{
//Method 3: with an anonmymous lambda.
//Concise enough, but it does not compile either...
container.ChangeContent([] (Content & c) { c.SetX(9); } );
std::cout << "x=" << container.GetContent().GetX() << std::endl;
}
*/
return 0;
}
My problem is that Methods 2 and 3 are more concise, but they will not compile. I wonder if there is hope to make them compile.
Can anyone help ?