Topic: Problems with template operators
Author: "Daniel Parker" <danielp@localhost.com>
Date: 1998/02/13 Raw View
First question:
Suppose I have the following class with two multiply operators defined:
template <class T>
class A
{
};
// (1) Operator for multiplying an A by a scalar, e.g. int, double
template <class T,class S>
A<T> operator*( const A<T>& a, const S& s )
{
return a;
}
// (2) Operator for multiplying an A by another A
template <class T>
A<T> operator*( const A<T>& a, const A<T>& b )
{
return a;
}
Now, supposing I attempt the following (using VC++ 5 with Service Pack 3):
A<double> a;
A<double> b;
A<double> c;
int x;
// (3)
b = a*x;
// (4)
c = a*b;
If I build with either (3) or (4) by themselves, everything works. If I
build with both (3) and (4), I get the error messages, referring to (4),
error C2667: '*' : none of 2 overload have a best conversion
error C2593: 'operator *' is ambiguous
If I modify (1), passing a value rather than a const reference, viz.
template <class T,class S>
A<T> operator*( const A<T>& a, S s )
{
return a;
}
everything works.
Comments? Is there a better way to write this?
Question 2:
For ordinary template functions, say
template <class T>
void f( T x )
{
}
one can force an explicit template instantiation with
template void f<double>( double x );
Should it be possible to do something similiar with template operators? In
the example (1) given above, trying
template A<double> operator*<double,int>( const A<double>& a, const S&
s );
leads to compile errors. Should this be legal?
Regards,
Daniel Parker
--
Please do not use reply, use danielp@anabasis.com instead.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]