C++ templated operators
The following code compiles under GNU C++:
#include <boost/shared_ptr.hpp> class A {}; class B : public A {}; template<typename T> T operator +(boost::shared_ptr<B> b) { return (T&)(b); } int main() { using namespace boost; shared_ptr<B> b(new B); shared_ptr<A> a; //a = +b; } If you un-comment the last line, however, it stops compiling. Is there a way to overload a unary operator (+ is a valid unary operator) within a template, and pass in the template parameters when the operator is used? I've tried the obvious a = +<A*>B; but that just gives a syntax error. (What I actually wanted to do was to pass in a functor to be run over every object in in a list, and use unary + to generate a total of whatever the functor returned; I thought this test case would be simpler code). Anyone know? Or is this simply a valid template that generates invalid code? |
What version of GCC do you have? It compiles for me; GCC reports v 4.1.0.
|
it compiles OK on cygwin and
SunOS primadtpdev 5.8 Generic_108528-20 sun4u sparc SUNW,Ultra-250 ???? gcc version 3.4.6 |
Sorry; the original post did compile. I thought I had reduced it to a proper test case as it didn't compile under GCC-2.96, but in 3.x series compiles it worked okay.
I have put a better use-case in an edit to the original post. This claims that there is no matching operator for + in +b in 4.1.2 (Ubuntu). Is it possible to pass a template parameter explicitly to an operator? |
Maybe you have to dereference b and then take its address; its type is shared_ptr<B>, whereas the + operator that you defined takes a "B &". I don't know about shared_ptr, so I don't know how you dereference it, but if they overload operator*, then you might have to do something like this:
Code:
a = +(&(*b)); |
Sorry; stupid mistake.
The operator should have taken a shared_ptr; I have corrected my example again. If you are intirested, the shared_ptr class is documented at http://www.boost.org/libs/smart_ptr/shared_ptr.htm And my example does now compile. I do still have a case that doesn't, but it's quite a large block of code and I think I've got a workaround anyway. If I can reduce it to a manageable test case when I have more time then I'll re-post. Sorry for wasting your time, and thanks for your help, |
All times are GMT -5. The time now is 07:01 AM. |