Re: Create objects
On 11 Mrz., 10:19, James Kanze <james.ka...@gmail.com> wrote:
On Mar 10, 2:57 pm, SG <s.gesem...@gmail.com> wrote:
On 10 Mrz., 13:32, "g3r...@gmail.com" <g3r...@gmail.com> wrote:
On Mar 9, 5:15 pm, Anarki <Deepchan...@gmail.com> wrote:
Is there a way to create an object by just knowing its type?
Here's just another suggestion: You could try to combine the
envelope/ letter idiom with the factory pattern in your case.
The "envelope" makes it easier to manage the polymorphic
object's life-time.
http://www.google.com/search?q=c%2B%2B+envelope+letter
http://www.google.com/search?q=factory+pattern
The envelope/letter pattern is designed so that polymorphic
objects can have value semantics. It's rarely needed, and has
considerable overhead.
Just to clearify: By "envelope/letter" I meant a pattern where the
handle object can manage polymorphic objects regardless of having
value or (counted) reference semantics. This is maybe not what you
had in mind.
Here's an example of what I was thinking of. In this case it actually
HAS value semantics but it doesn't have to.
----------8<----------
#include <algorithm>
#include <string>
class LetterBase {
public:
virtual ~LetterBase() {}
virtual double foo(double x) const = 0;
virtual void tweak(double p) = 0;
virtual LetterBase* clone() const = 0;
};
class Envelope {
LetterBase* ptr;
public:
explicit Envelope(LetterBase* p=0) : ptr(p) {}
Envelope(Envelope const& e)
: ptr(e.ptr==0 ? 0 : e.ptr->clone()) {}
~Envelope() {delete ptr;}
void swap(Envelope& with) {std::swap(ptr,with.ptr);}
Envelope& operator=(Envelope e) {swap(e); return *this;}
double foo(double x) const {return ptr->foo(x);}
void tweak(double p) {ptr->tweak(p);}
};
inline void swap(Envelope& a, Envelope& b) {a.swap(b);}
/// creates an Envelope object -- possibly delegating
/// the creation of a LetterBase-derived object according
/// to the given string parameter.
Envelope factory(std::string const& blah);
int main()
{
Envelope e = factory("bar42");
double y1 = e.foo(23.1);
e.tweak(99.0);
double y2 = e.foo(23.1);
}
----------8<----------
This looks pretty much like the code I wrote a couple of weeks ago.
It combines the "compiler firewall" idiom with polymorphism and value
semantics. In my case it was quite useful. The overhead is moderate
and it doesn't affect the performance of typical client code I have in
mind.
Cheers!
SG