Home Optional "name" in parameter-list?
Reply: 0

Optional "name" in parameter-list?

user9892
1#
user9892 Published in September 21, 2018, 8:22 am

template < parameter-list > declaration

Each parameter in parameter-list may be:

  • a non-type template parameter;
  • a type template parameter;
  • a template template parameter.

Minutes ago, I found

  • template<typename>/*(a type template parameter)*/
  • template<int>/*a non-type template parameter*/

are legal in some cases.

So, syntax is like:

  • a type template parameter;
    • typename name(optional)
  • a non-type template parameter;
    • type name(optional)
  • ...

Here is an example

template <typename T>
class ArrayList
{
    std::vector<T> vec;
public:
    template<class> // Mark!
    class Ref {
        ArrayList<T> *array;
        int position;
    public:
        Ref(ArrayList<T> *a, int pos):array(a), position(pos) {};
        Ref<T> &operator=(T v) {
            if (array->vec.size() <= position)
                array->vec.resize(position+1);
            array->vec[position] = v;
        }
        operator T() const {
            if (array->vec.size() <= position)
                throw std::exception();
            return array->vec[position];
        }
    };
    Ref<T> operator[](int p) {return Ref<T>(this, p); }; 
};

I know similar idiom in function's parameter type fun(type) {}, the only usage of it is we don't need the name, type is enough here.

My question is:

  1. In the implementation of Ref, What is the benefit of template<class> instead of template<class T> or template<class U>. I guess that it is because we don't need extra T/U here(Precisely, it is U, because extra T will cause shadowing error) template <typename T> class ArrayList
  2. What're the other benefits of the idiom?(Of course, perhaps no other benefits)
  3. Except for injected class, when will we exclude the redundant name in parameter-list. I hope to see more applications.
share|improve this question
  • One example of when you leave out the name is if you add an extra typename = void and use SFINAE on that parameter to select the correct specialization. – super Feb 11 at 10:53
  • You know, after writing one example, I'm starting to think this may be too broad. – StoryTeller Feb 11 at 11:09
  • Emmm, do you refer to tag dispatch I don't think so. As an idiom, tag dispatch is not broad to be treated as an example here. If you refer to my question is too broad, I do agree :P – 陳 力 Feb 11 at 11:18

2 Answers 2

active oldest votes
up vote 1 down vote
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO