Search code examples
c++variadic-templates

Expand variadic template fold expression


template<typename... Ts>
using Type = std::variant<std::shared_ptr<T1>, std::shared_ptr<T2>, std::shared_ptr<Tn>>;

How I can do this using variadic templates and fold expressions?

I try something like this:

template<typename... Ts>
using Type = std::variant<((std::shared_ptr<Ts>), ...)>;`

but it doesn't compile.


Solution

  • The following compiled for me

    template<typename... Ts>
    using Type = std::variant<std::shared_ptr<Ts>...>;
    

    As stated here

    A pattern followed by an ellipsis, in which the name of at least one parameter pack appears at least once, is expanded into zero or more comma-separated instantiations of the pattern, where the name of the parameter pack is replaced by each of the elements from the pack, in order

    Here our pattern is std::shared_ptr<Ts>, which is expanded into std::shared_ptr<T1>, std::shared_ptr<T2>, std::shared_ptr<Tn>