Reloading of indexation



  • There's a class:

    class A
    {
       public:
         int& operator [] (int a)
         {
            return x.at(a);
         }
         int operator [] (int a) const
         {
            return x.at(a);
         }
       private:
         vector<int> x;
    };
    

    Since both overloads are the same, I want to combine them into a template. Can we do that?



  • No.

    Although these two methods contain the same text, they are completely different: one working on a constant object and returning the whole number by producing a constant method at; the other working on a non-constant object, returning the reference from a non-constant method at. In general, they have different signatures and different implementations.

    By the way, usually overloads do the following:

    int& operator [] (int a)
    const int& operator [] (int a) const
    

    Shablons suggest that the class is grouped according to a certain parameter (or weight). There's nothing to do with it. Well, if you want your class to be supportive, not only. intYou can make a template:

    template <typename T>
    class A
    {
       public:
         T& operator [] (int a)
         {
            return x.at(a);
         }
         const T& operator [] (int a) const
         {
            return x.at(a);
         }
       private:
         vector<T> x;
    };
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2