以下是我从另一个问题中获取的示例,我理解为什么这不起作用:
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
}
这没用。任何人都可以对此有所了解吗?模板快把我逼疯了。
谢谢。