类模板上的运算符重载

时间:2023-04-24
本文介绍了类模板上的运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我在为模板类定义一些运算符重载时遇到了一些问题.让我们以这个假设的类为例.

I'm having some problems defining some operator overloads for template classes. Let's take this hypothetical class for example.

template <class T>
class MyClass {
  // ...
};

  • 运算符+=

    • operator+=

      // In MyClass.h
      MyClass<T>& operator+=(const MyClass<T>& classObj);
      
      
      // In MyClass.cpp
      template <class T>
      MyClass<T>& MyClass<T>::operator+=(const MyClass<T>& classObj) {
        // ...
        return *this;
      }
      

      导致此编译器错误:

      no match for 'operator+=' in 'classObj2 += classObj1'
      

    • 运算符<<

    • operator<<

      // In MyClass.h
      friend std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj);
      
      
      // In MyClass.cpp
      template <class T>
      std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj) {
          // ...
          return out;
      }
      

      导致此编译器警告:

      friend declaration 'std::ostream& operator<<(std::ostream&, const MyClass<T>&)' declares a non-template function
      

    • 我在这里做错了什么?

      推荐答案

      // In MyClass.h
      MyClass<T>& operator+=(const MyClass<T>& classObj);
      
      
      // In MyClass.cpp
      template <class T>
      MyClass<T>& MyClass<T>::operator+=(const MyClass<T>& classObj) {
        // ...
        return *this;
      }
      

      这对模板无效.运算符的完整源代码必须在使用它的所有翻译单元中.这通常意味着代码内联在标头中.

      This is invalid for templates. The full source code of the operator must be in all translation units that it is used in. This typically means that the code is inline in the header.

      从技术上讲,根据标准,可以导出模板,但是很少有编译器支持它.此外,如果模板在 MyClass.cpp 中为所有 T- 类型显式实例化,您也可以执行上述操作,但实际上,这通常无视模板的要点.

      Technically, according to the Standard, it is possible to export templates, however very few compilers support it. In addition, you CAN also do the above if the template is explicitly instantiated in MyClass.cpp for all types that are T- but in reality, that normally defies the point of a template.

      更多我通读了你的代码,它需要一些工作,例如重载运算符 [].此外,通常,我会将维度作为模板参数的一部分,允许在编译时捕获 + 或 += 的失败,并允许有意义地堆栈分配类型.您的异常类还需要从 std::exception 派生.然而,这些都不涉及编译时错误,它们只是不是很好的代码.

      More edit: I read through your code, and it needs some work, for example overloading operator[]. In addition, typically, I would make the dimensions part of the template parameters, allowing for the failure of + or += to be caught at compile-time, and allowing the type to be meaningfully stack allocated. Your exception class also needs to derive from std::exception. However, none of those involve compile-time errors, they're just not great code.

      这篇关于类模板上的运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:不完整类型的无效使用 下一篇:为什么关键字“typename"是需要在限定的从属名

相关文章

最新文章