Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent interface pattern and std::unique_ptr

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.

like image 933
Cristiano Avatar asked Dec 12 '22 02:12

Cristiano


1 Answers

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();
}
like image 152
Benjamin Lindley Avatar answered Dec 28 '22 08:12

Benjamin Lindley