Search code examples
c++c++11operator-overloadingvariadic-templatessubscript-operator

variadic templated overload of operator [] in templated class


I am trying to overload the operator[]. The following code does not compile and I suspect I'm just making a syntax mistake, but I need help understanding what I'm doing wrong and why.

Here is an excerpt of the relevant code:

template <typename T>
class MultiDimArray{
public:
  template <typename ...I>
  T& operator[](const size_t firstIndex,const size_t ...I);
  //...
}

template <typename T> //class's template parameter(s)
template <typename ...I> //function's template parameter(s)
T& MultiDimArray<T>::operator[](const size_t firstIndex,const size_t ...I){
  //...
}

Note1: I'm trying to follow the compile time convertible to type checking suggested at the top of this answer.


Solution

  • operator[] can only take one argument, the easiest solution is to overload operator() instead and access members via () instead of [].

    The proper syntax would then be:

        template <class T>
        template <class ... I>
        T& MultiDimArray<T>::operator()(I ... i)
        {
        }
    

    You were also using the types list I as though they were parameter names instead of type names (which is fixed in my example).