好吧,也許我的問題是一點點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'。 –
我喜歡你的解決方案,因爲我可以避免使用函數指針的錯綜複雜的語法來搔癢我的頭。 –