Operator overloading on class templates

后端 未结 5 1592
孤城傲影
孤城傲影 2020-12-01 05:47

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

template 
cl         


        
5条回答
  •  天涯浪人
    2020-12-01 06:22

    // In MyClass.h
    MyClass& operator+=(const MyClass& classObj);
    
    
    // In MyClass.cpp
    template 
    MyClass& MyClass::operator+=(const MyClass& 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.

    Edit: 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.

    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.

提交回复
热议问题