不匹配运算符 [] 错误

no match for operator[] error

我一直在试验 C++ 中的操作重载,并且尝试使用模板。但是我得到了这个错误: error: 'operator[]' in 'a[4]'
不匹配 这是我的代码:

#include "JSE.h"
#include <iostream>
using namespace std;

struct obj{
    int l;
    template<typename varname>
    varname operator[] (int n){
        return (this->l)+n;
    }
};

int main(void){
    obj a;
    a.l=20;
    cout<<a[4];
    return 0;
}

而且我只有在使用模板时才会收到此错误。例如,此代码有效:

#include "JSE.h"
#include <iostream>
using namespace std;

struct obj{
    int l;
    int operator[] (int n){
        return (this->l)+n;
    }
};

int main(void){
    obj a;
    a.l=20;
    cout<<a[4];
    return 0;
}

是什么导致了错误,我该如何解决?
注意:我真的很想保留模板,因为我将在未来的项目中将其与运算符重载一起使用。

为了使模板推导工作,编译器必须能够以某种方式推断出您正在使用的类型。

template<typename varname>
varname operator[] (int n){
    return (this->l)+n;
}

不允许这样做,因为您正在模板化的唯一内容是 return 类型。编译器无法知道您想要什么类型作为 return 类型,因此您会收到类似 this.

的错误

如果您改为在函数参数中使用模板类型,那么编译器可以推断出模板类型,因为它可以使用传递给函数的类型。

#include <iostream>
using namespace std;

struct obj{
    int l;
    template<typename varname>
    varname operator[] (varname n){
        return (this->l)+n;
    }
};

int main(void){
    obj a;
    a.l=20;
    cout<<a[4];
    return 0;
}

Live example

问题是对于第一个程序,编译器无法确定运算符的 return 类型。

您只能像

那样调用接线员
obj a;
a.l=20;
std::cout<< a.operator []<int>( 4 ) << std::endl;

按以下方式更改 class 定义

template<typename varname>

struct obj{
    varname l;
    varname operator[] (int n){
        return (this->l)+n;
    }
};

在main中会有这样的代码

obj<int> a;
a.l=20;
cout<<a[4];