Sign in to follow this  
ndwork

Left Multiply by templated parameter

Recommended Posts

I have a container class. I would like to left and right multiply this class by both literal values and other classes. That is, I would like to do something like what follows.
template <class T>
class myClass {
  myClass();
  template <class U> const myClass<T> operator *( const U &value ) const;
  template <class U> friend const myClass <U> operator *( const U &value, const myClass <U> &in );
  template <class S> const myClass<T> operator *( const myClass<S> &in ) const;
};

When I do that though, I get an error when I try to do something like 'myClass<double> = 8 * classInstance'. The error statment is as follow:
Quote:
template parameter U is ambiguous
I suspect that it is ambiguous because U can be an element of type myClass. Is there some way to do this? Where left and right multiplication by an object of type myClass is one set of functions, and left and right multiplication of everything else is a different set of functions? As always, thank you all for your help.

Share this post


Link to post
Share on other sites
It is most probably ambigous, since 8 is an int and classinstance is most probably myClass<double>. So what is U: int or double? (All the other overloads accept independent types for some reason.)

Template friends are can be tricky though. Wouldn't it be possible to implement simple * complicated as a free non-friend function that simply calls complicated * simple?

Share this post


Link to post
Share on other sites
Quote:
Original post by visitor
It is most probably ambigous, since 8 is an int and classinstance is most probably myClass<double>. So what is U: int or double? (All the other overloads accept independent types for some reason.)

Implicit conversion is not done when attempting to match template parameters.

Rewrite the friend function with two template parameter types:


template <class U, class V> friend const myClass <U> operator *( const V &value, const myClass <U> &in );




This will defer the implicit conversion until you actually perform the multiplication inside the body, where it is allowed.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this