1

Take the following snippet as a base:

template<typename Type1, typename Type2>
auto Foo() {
    std::tuple<std::shared_ptr<Type1>, std::shared_ptr<Type2>> example;
}

How should I go about creating my tuple of shared pointers when using a variadic template?

template<typename... Types>
auto Foo() {
    // How to create the tuple?
}

There are tons of tuple and variadic template related questions here. Some seem to address this (link1, link2), but still feel too convoluted (honestly, the answers went over my head, but may well be the simplest way).

My attempt used recursive templates and std::tuple_cat, but this creates many "sub-tuples" along the way, which is far from ideal.

In short: is there a "simpler" or "more direct" approach to this problem? Something that doesn't require multiple functions, recursive calls and whatnot, kinda like std::tuple<std::shared_ptr<Types...>>?

vlucki
  • 49
  • 5

1 Answers1

5

Expand the pack:

#include <tuple>
#include <memory>
#include <type_traits>

template<typename... Types>
auto Foo() {
   using tup = std::tuple<std::shared_ptr<Types>...>;
   return tup{};
}

int main() {
  auto f = Foo<int,double>();
  static_assert( std::is_same_v< std::tuple<std::shared_ptr<int>,std::shared_ptr<double>>,decltype(f)>);
}

For convenience you can use an alias:

#include <tuple>
#include <memory>
#include <type_traits>

template <typename...Types>
using SharedTuple = std::tuple<std::shared_ptr<Types>...>;

int main() {
  static_assert( std::is_same_v< std::tuple<std::shared_ptr<int>,std::shared_ptr<double>>,SharedTuple<int,double>>);
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • So you're saying I almost got it right with my example? I had no idea this was a thing, please imagine a thunderclap as I facepalm hard. – vlucki Feb 04 '21 at 13:04