我在为模板类定义一些运算符重载时遇到了一些问题.让我们以这个假设的类为例.
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模板网!
std::reference_wrapper 和简单指针的区别?Difference between std::reference_wrapper and simple pointer?(std::reference_wrapper 和简单指针的区别?)
常量之间的区别.指针和引用?Difference between const. pointer and reference?(常量之间的区别.指针和引用?)
c++ - 如何从指向向量的指针访问向量的内容?How to access the contents of a vector from a pointer to the vector in C++?(c++ - 如何从指向向量的指针访问向量的内容?)
*& 的含义和**&在 C++ 中Meaning of *amp; and **amp; in C++(*amp; 的含义和**amp;在 C++ 中)
为什么我不能对普通变量进行多态?Why can#39;t I do polymorphism with normal variables?(为什么我不能对普通变量进行多态?)
取消引用已删除的指针总是会导致访问冲突?Dereferencing deleted pointers always result in an Access Violation?(取消引用已删除的指针总是会导致访问冲突?)