【发布时间】:2020-09-08 23:50:30
【问题描述】:
我正在尝试重载模板类中的 [int] 运算符,但我总是收到 C2676 错误,然后是 Visual Studio E0349“没有运算符 [] 匹配这些操作数 WMSTR [int]”
我的模板类:
template <typename T, unsigned int N>
class MyString{
public:
// ... Non relevant tested code
template<typename T, unsigned int N>
T& operator[](int index) {
// Assert index size
SLOW_ASSERT(index >= 0 && index < N);
// Return current value
return m_buffer[index];
}
template<typename T, unsigned int N>
const T& operator[](int index) const {
// Assert index size
SLOW_ASSERT(index >= 0 && index < N);
// Return current value
return m_buffer[index];
}
private:
T m_buffer[N];
}
SLOW_ASSERT(...) 只是 assert(...) 的包装器
主要内容:
#include "path_to_template.h"
typedef MyString<wchar_t, 24> WMSTR;
int main(void){
WMSTR str = L"Test";
str[0] = L'X'; // <-- Error here
return 0;
}
【问题讨论】:
标签: c++ templates visual-c++ operator-overloading