0

I was reviewing my code, and I found out that i use often these constructs:

std::shared_ptr<std::vector<shared_ptr<ClassA>>>

auto instance = std::make_shared<std::vector<shared_ptr<ClassB>>>() etc.

Is there a valid opportunity to set a shortcut for the std::make_shared<std::vector<shared_ptr<$CLASSNAME$>>> or std::shared_ptr<std::vector<shared_ptr<$CLASSNAME$>>> phrase?

something like using svs<ClassA> = std::shared_ptr<std::vector<shared_ptr<ClassA>>> (invalid syntax; does not compile!)

Is there another opportunity, than using a template?

Greets

p.dev
  • 1

2 Answers2

3

Is there another opportunity, than using a template?

No; a template is literally what you're asking for.

This is correct:

template <typename ClassA>
using svs<ClassA> = std::shared_ptr<std::vector<shared_ptr<ClassA>>>;

There is no other way to make it work unless you write lots of different aliases yourself for different cases.

As an aside, that's a lot of indirection. Are you sure you need so many layers of shared_ptr?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • Well, not quite _literally_ - it's a template _alias_ that should be used here, not a (new) template. – Max Langhof Jan 10 '20 at 13:12
  • 2
    @MaxLanghof The standard calls them "alias templates" (c.f. function templates, class templates); I think it's reasonable to think of these things as kinds of templates. cppref also says _"An alias template is a template which [..]"_ – Lightness Races in Orbit Jan 10 '20 at 13:18
  • Ok, I concede :D – Max Langhof Jan 10 '20 at 13:19
  • Thanks for your answer. Due to your question "_As an aside, that's a lot of indirection. Are you sure you need so many layers of shared_ptr?_": I need to handle variable numbers of ClassA. I have access them via pointer and using a vector around these ClassA-Instances. Would you consider this a "not clean" code? Is there a better way? I would be happy about corrections :) – p.dev Jan 13 '20 at 07:43
  • @p.dev It's a suspicious choice of type but I cannot "correct" it or other suggest replacements without auditing your code and knowing what it does – Lightness Races in Orbit Jan 13 '20 at 10:27
2

With template alias, you might do:

template <typename T>
using svs = std::shared_ptr<std::vector<std::shared_ptr<T>>>;
Jarod42
  • 203,559
  • 14
  • 181
  • 302