Search code examples
c++templatesc++17parameter-pack

How can one construct an object from a parameter pack in a C++ template?


Given the following, how can I correctly construct an object of an unknown type from a parameter pack?

template < typename... Types >
auto foo( Types&&... types ) {
    auto result =  Types{ }; // How should this be done?
    // Do stuff with result
    return result;
}

I expect the template function to only be called with matching types, so everything in the parameter pack should be of the same type. It doesn't matter which individual item I reference if I need to use decltype, for example (relevant code in the commented out section will cause compilation errors otherwise).


Solution

  • Since all the types in the parameter pack are the same, you can first use the comma operator to expand the parameter pack, then use decltype to get the type of the last operand.

    template<typename... Types>
    auto foo(Types&&... types) {
      auto result = decltype((Types{}, ...)){ };
      // Do stuff with result
      return result;
    }
    

    Demo.