LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C++ templated operators (https://www.linuxquestions.org/questions/programming-9/c-templated-operators-574473/)

rjlee 08-03-2007 07:40 AM

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?

sjr 08-03-2007 09:10 AM

What version of GCC do you have? It compiles for me; GCC reports v 4.1.0.

bigearsbilly 08-03-2007 09:13 AM

it compiles OK on cygwin and
SunOS primadtpdev 5.8 Generic_108528-20 sun4u sparc SUNW,Ultra-250


????

gcc version 3.4.6

rjlee 08-03-2007 03:06 PM

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?

sjr 08-03-2007 06:18 PM

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));
or maybe just "a = +(*b);" will work. Or you can redefine operator+ to accept a shared_ptr<B> and return a shared_ptr<A>.

rjlee 08-04-2007 05:17 AM

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.