I am playing with the fluent interface pattern.
First, I wrote something like that:
class C
{
public:
C() { }
C* inParam1(int arg1){ param1 = arg1; return this; }
C* inParam2(int arg2){ param2 = arg2; return this; }
private:
int param1;
int param2;
}
Then I tried to use the std::unique_ptr, but then I realized that I do not know how to "shift" the pointer (this) along the chain. I tried something like:
return std::move(this);
that of course does not work.
How can I do this? Are there any problems doing something like this?
In order to reply to comments like: "do not use pointers": there isn't (yet) any practical reason because I am doing this with pointers, is just something I wonder if can be done this way.
Why do you have to return pointers at all?
class C
{
public:
C create() { return C(); }
C & inParam1(int arg1){ param1 = arg1; return *this; }
C & inParam2(int arg2){ param2 = arg2; return *this; }
private:
C() { }
int param1;
int param2;
};
I must admit I don't understand the purpose of that create function or why the constructor is private or how you actually create objects of this class at all. In my understanding, the class should actually be like this:
class C
{
public:
C() {}
C & inParam1(int arg1){ param1 = arg1; return *this; }
C & inParam2(int arg2){ param2 = arg2; return *this; }
private:
int param1;
int param2;
};
And used like this:
int main()
{
C().inParam1(10).inParam2(20).whatever();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With