【问题标题】:Template operator[] overloading strange C2676模板运算符 [] 重载奇怪的 C2676
【发布时间】: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


    【解决方案1】:

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

    将它们设为非模板应该可以正常工作;我想你只是想在operator[]中引用类模板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];
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 2022-10-01
      • 2014-02-02
      相关资源
      最近更新 更多