Search code examples
c++shared-ptrvariadic-functions

Passing shared_ptr via variable argument list


Is this possible to do and how would I pass the shared_ptr(s)? I found some related question (C++ variable number of arguments) but it does not fully address my question. I have tried a few ways to write such function but all I get is an error error: cannot receive objects of non-trivially-copyable type ‘class std::shared_ptr<Item>’ through ‘...’;

If this is not a good idea at all, how could I pass an arbitrary number of shared_ptr's as an an argument, almost something like variadic templates or such? Maybe this is even more simple than I think ...

Thanks for your help!


Solution

  • With C++11 you can either use variadic templates or initializer lists. Initializer lists are a bit easier to use, because they do not require recursion and they can be defined in separate compilation units:

    void foobar(std::initializer_list<std::shared_ptr<widget>> widgets);
    
    std::shared_ptr<widget> foo;
    std::shared_ptr<widget> bar;
    foobar({ foo, bar });