好吧,也许我的问题是一点点conveved。C++ 11/lambda函数和函数指针
我想找到一个优雅的解决方案,以减少以下样板代码,每次我想修改一个对象的一部分,只能通过一个const Getter和一个非const设置器访问。
Content c = container.GetContent();
c.SetX(3);
container.SetContent(c);
我知道我可以有一个非const的getter,但我想暂时坚持下去。
所以,我试图用lambda表达式,我目前有以下实现:
#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;
}
我的问题是方法2和3是更简洁,但他们不会编译。 我不知道是否有希望让他们编译。
任何人都可以帮忙吗?
@woolstar本地对象永远不会被引用返回。在这种情况下'this'是const的,所以我们不能修改它返回'* this'。 –
我喜欢你的解决方案,因为我可以避免使用函数指针的错综复杂的语法来搔痒我的头。 –