Home How to declare pointers/references to template class member types?
Reply: 1

How to declare pointers/references to template class member types?

piripiri
1#
piripiri Published in 2017-12-06 13:09:05Z

I hope the title is not too far off. Consider the following piece of code:

template<class C>
struct Wrapper {
  using type = C;
};

int main()
{
  Wrapper<int>::type *a;
  Wrapper<int*>::type b;
  int i;
  Wrapper<int>::type &c = i;
  Wrapper<int&>::type d = i;
}

Here, * and & can either go into the template argument or can be attached to the variable name. While I think both ways of declaring have the same effect, this is just my question:

Are the different ways of declaring pointers/references equivalent or are there situations in which one of them is preferred over the other for whatever reasons (e.g. safer, compiles faster, better style, ...)?

Jodocus
2#
Jodocus Reply to 2017-12-06 13:23:06Z

Are the different ways of declaring pointers/references equivalent or are there situations in which one of them is preferred over the other for whatever reasons (e.g. safer, compiles faster, better style, ...)?

Not preferred, but they can yield actually different results. Think of partial specialization:

template <typename T>
struct Resource_wrapper {
    using type = T;
};

template <typename T>
struct Resource_wrapper<T*> {
   using type = std::unique_ptr<T>;
};

Here, it makes a great difference between writing Resource_wrapper<int>::type* and Resource_wrapper<int*>::type.

Or consider std::unique_ptr<>, which also uses partial specialization:

std::unique_ptr<int[]> ptr; // smart pointer managing integer array
std::unique_ptr<int> ptr[5]; // array of five integer smart pointers
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.318572 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO