좋아, 아마도 내 문제는 조금 contrieved입니다.C++ 11/lambda 함수 및 함수 포인터
const Getter 및 non const Setter를 통해서만 액세스 할 수있는 객체의 일부를 수정하고 싶을 때마다 다음 상용구 코드를 줄이기 위해 우아한 솔루션을 찾으려고합니다.
Content c = container.GetContent();
c.SetX(3);
container.SetContent(c);
나는 const가 아닌 게터를 가질 수는 있지만 시간이 지날수록 좋습니다.
그래서, 람다를 사용하려하고 나는 현재 다음과 같은 구현이 있습니다
#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 방법은보다 간결 있다는 것입니다,하지만 그들은 컴파일되지 않습니다. 컴파일 할 수있는 희망이 있는지 궁금합니다.
아무도 도와 줄 수 있습니까? 이 선언에서 &
을 제거하고 작동합니다 :
void ChangeContent(ContentFunctionChanger &function)
(물론, 당신은 또한 func
에 func2
의 이름을 변경해야합니다
@woolstar 로컬 객체는 참조로 반환되지 않습니다. 이 경우'this'는 const이므로'* this'를 반환하도록 수정할 수는 없습니다. –
함수 포인터의 복잡한 구문으로 머리를 긁적 거리지 않도록 템플릿을 사용하여 솔루션을 좋아합니다. –