Search code examples
c++raiivisitor-patternvariadic

C++ function to create and destroy temporary with given type and constructor parameters


I'm finding a lot of the following in my code:

{
    SomeClass<VisitorType> obj(visitor, param1, param2, 3, 4);
}
{
    OtherClass<VisitorType> obj(visitor, 5, "six");
}

The braces are necessary to ensure that the object's lifetime is constrained work is done in constructor and destructor (RAII style). There is good reason for this and other users of these class templates do more than just construct and destruct.

Is there a convenient idiom to boil this down to something like a function call, where possible retaining strong typing?

e.g.

f<SomeClass>(visitor, param1, param2, 3, 4);
f<OtherClass>(visitor, 5, "six");

where f<>() is something like:

template <template <class> class C, class V>
void f(V &v, ...)
{
    C<V> c(v, ...); // magic needed here
}

I tried using variadic functions but hit a load of compilation errors. I would prefer not to use macros if possible. Thanks!


Solution

  • What about

    SomeClass<VisitorType>(visitor, param1, param2, 3, 4);
    

    This seems to work for me.

    However, I wouldn't leave such a line of code in some function without providing a comment explaining that leaving out the object was intentional. A function, on the other hand, would be a convenient place to put such documentation:

    // call C<V>'s ctor, leaving the caller to decide when to call dtor
    template<template <class> class C, typename V, typename... Args>
    C<V> fire_and_forget(V& visitor, Args&&... args) {
      return C<V>(visitor, std::forward<Args>(args)...);
    }
    

    Then use it thus:

    fire_and_forget<SomeClass>(visitor, param1, param2, 3, 4);