8

In our codebase we use std::variant<std::shared_ptr<SomeClass>, ...> a lot.

That obviously requires a lot of writing. How to make a template?

template <class... T>
using VarSP = std::variant<std::shared_ptr<???>>;

Where should T go in the above snippet? The desired behavior should be:

VarSP<Foo, Bar, Baz> // std::variant<std::shared_ptr<Foo>, std::shared_ptr<Bar>, std::shared_ptr<Baz>>
Nurbol Alpysbayev
  • 19,522
  • 3
  • 54
  • 89
  • 2
    I'm curious what you tried. There are really not that many options here if you have seen any variadic templates before... – Max Langhof Sep 02 '19 at 09:42
  • @MaxLanghof Honestly I didn't have any idea other than the snippet you can see in the question. Also, I am only learning C++ for a week or so, so I didn't even know it is called variadic template (therefore couldn't google properly). – Nurbol Alpysbayev Sep 02 '19 at 09:43
  • 2
    If you're only in your first or second week of C++ programming and already using template packs, that seems you're getting a little ahead of yourself. Slow down, perhaps even take a step or two back, [get a couple of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) and continue forward in a slower pace while learning the basics first. – Some programmer dude Sep 02 '19 at 09:53
  • @Someprogrammerdude Thanks for advice! In my case I only need to make a small node.js C++ addon, quick and dirty. I am also an advanced user of TypeScript that's why the concept of templates is not so hard to me (they're much like TS' generics). That said, I'd *love* to read some modern C++ books, but I am a contestant at a rat race called "Life in a developing country", so I can't afford this yet. – Nurbol Alpysbayev Sep 02 '19 at 10:01
  • 1
    *"we use `std::variant, ...>` a lot."*, nearly, just remove extra comma ;-) – Jarod42 Sep 02 '19 at 10:47

1 Answers1

15
template <typename... T>
using VarSP = std::variant<std::shared_ptr<T>...>;
user7860670
  • 35,849
  • 4
  • 58
  • 84