模板运算符 [] 重载奇怪 C2676

Template operator[] overloading strange C2676

我试图在模板 class 中重载 [int] 运算符,但我总是收到 C2676 错误,然后是 visual studio E0349 "no operator [] matches these operands WMSTR [ int ]"

我的模板class:

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;
}

您将 operator[] 都声明为函数模板,无法推导它们的模板参数,然后调用失败。

将它们设为非模板应该没问题;我想您只想参​​考 operator[].

中 class 模板 MyString 的模板参数 TN
T& operator[](int index) {
    // Assert index size
    SLOW_ASSERT(index >= 0 && index < N);
    // Return current value
    return m_buffer[index];
}

const T& operator[](int index) const {
    // Assert index size
    SLOW_ASSERT(index >= 0 && index < N);
    // Return current value
    return m_buffer[index];
}