I decided to use builder pattern to avoid long unnamed-arguments constructor, but I have a specific use case for it. I have a base class and some inherited class from it which all of them must be able to construct separately. Below show a pseudo-code explain my special use case:
class B
{
int i;
int j;
public:
B& setI(int i) {this->i=i; return *this;}
B& setJ(int j) {this->j=j; return *this;}
}
class I : public B
{
int i2;
int j2;
public:
I& setI2(int i) {this->i2=i; return *this;}
I& setJ2(int j) {this->j2=j; return *this;}
}
B b = B().setI(12).setJ(13); // ok
I i = I().setI(12).setJ(13).setI2(14).setJ2(15); // error the first and second function return B not I
The above code could not be compiled because the functions in B do not return a type of class I. A solution has been suggested in this post, but it is limited and it is not possible to create the base class separately. I am using c++11 but it is possible to use another version of c++.
Aucun commentaire:
Enregistrer un commentaire