I would like to write an object generator for the RAII template class - basically a function template for constructing an object using the type inference method, t should be specified explicitly.
The problem that I foresee is that a helper function that takes care of type inference for me will return the object by value, which (**) will cause the RAII destructor to be called prematurely when copying. Maybe C ++ 0x move semantics might help, but this is not an option for me.
Has anyone seen this problem before and has a good solution?
This is what I have:
template<typename T, typename U, typename V> class FooAdder { private: typedef OtherThing<T, U, V> Thing; Thing &thing_; int a_;
The bottom line is that OtherThing has a terrible interface, and FooAdder should make it easier to use. Intended use is something like this:
FooAdder(myThing, 2) .foo(3, 4) .foo(5, 6) .bar(7) .foo(8, 9);
The FooAdder constructor initializes some internal data structures. The foo and bar methods populate these data structures. ~FooAdder dtor wraps things and calls a method on thing_ , taking care of all the nasty things.
This will work fine if FooAdder not a template. But since this is the case, I will need to introduce types that are more similar to this:
FooAdder<Abc, Def, Ghi>(myThing, 2) ...
This is annoying because types can be inferred based on myThing . Therefore, I would prefer to create a template object generator similar to std::make_pair , which will std::make_pair type inference for me. Something like that:
template<typename T, typename U, typename V> FooAdder<T, U, V> AddFoo(OtherThing<T, U, V> &thing, int a) { return FooAdder<T, U, V>(thing, a); }
This seems problematic: since it returns a value, the temporary stack object will be (**) destroyed, which will cause the RAI dtor to start prematurely.
** - if RVO is not implemented. Most compilers do, but this is not required, and you can disable them in gcc using -fno-elide-constructors .