2

我想重载运算符[]。下面的代码不能编译,我怀疑我只是犯了一个语法错误,但我需要帮助理解我在做什么错误以及为什么。在模板类中运算符[]的可变模板超载

下面是相关代码的摘录:

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){ 
    //... 
} 

注1:我想按照编译时转换为类型在this answer顶端检查建议。

+0

另请参阅http://www.parashift.com/c++-faq/matrix-subscript-op.html – dyp

回答

4

operator[]只能采取一个参数,最简单的解决方案是重载operator()而不是()而不是[]访问成员。然后

正确语法是:

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

你也使用类型列表I就好像它们是参数名称,而不是类型名称(这是在我的例子固定)。