以下是我从另一个问题中获取的示例,我明白为什么这不起作用:
struct Foo {
Foo() {}
Foo(int) {}
Foo operator+(Foo const & R) { return Foo(); }
};
struct Bar {
Bar() {}
Bar(int) {}
};
Bar operator+(Bar const & L, Bar const & R) {
return Bar();
}
int main() {
Foo f;
f+1; // Will work - the int converts to Foo
1+f; // Won't work - no matching operator
Bar b;
b+1; // Will work - the int converts to Bar
1+b; // Will work, the int converts to a Bar for use in operator+
}
但是,如果我将其更改为以这种方式使用模板:
template <class T>
struct Foo {
Foo() {}
Foo(T) {}
Foo operator+(Foo const & R) { return Foo(); }
};
template <class T>
struct Bar {
Bar() {}
Bar(T) {}
};
template <class T>
Bar operator+(Bar const & L, Bar const & R) {
return Bar();
}
int main() {
Foo<int> f;
f+1; // Will work - the int converts to Foo
1+f; // Won't work - no matching operator
Bar<int> b;
b+1; // DOES NOT WORK
1+b; // DOES NOT WORK
}
它不起作用。有人能解释一下吗?模板快把我逼疯了。
谢谢。
最佳答案
有两个问题。
- 您需要将模板类型添加到运算符定义中的参数中。这是必要的,因为它需要使用它们来知道要使用哪个 Bar 实例。
- 如果您希望在模板函数中使用混合运算符(对两种不同的类型进行操作),则需要提供所有混合情况的定义。否则,模板推演系统将无法按照您想要的方式工作。
.
template <class T>
Bar<T> operator+(Bar<T> const & L, Bar<T> const & R) { // Fixed
return Bar<T>();
}
template <class T>
Bar<T> operator+(Bar<T> const & L, const T & R) { // Added
return L + Bar<T>(R);
}
template <class T>
Bar<T> operator+(const T& L, Bar<T> const & R) { // Added
return Bar<T>(L) + R;
}
关于C++:运算符和模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11530151/