# 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 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 on other sites
Quote:
 Original post by visitorIt is most probably ambigous, since 8 is an int and classinstance is most probably myClass. 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 on other sites
This did indeed work. Thank you.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628294
• Total Posts
2981876

• 11
• 10
• 10
• 11
• 17