Re: template classes and implicit conversion
* alexroat:
Hi,
I cant understand why this code does not work.
I've implemented two classes A,B that provide an array like structure
(they are identical).
I can convert B in A using implicit conversion, but it works only in
argument passing in non-template function (in this case the commented
sum) but not with the same expressed in template form (uncommented
sum).
This code wont compile, uncommenting the specialized sum function it
would do instead.
the error is " error: no matching function for call to `sum(B<int,
4u>&)' "
There's an explanation at this strange behavior or is a compiler bug
(mine is gcc (GCC) 3.4.6 20060404 (Red Hat 3.4.6-8) ) ?
See below.
Thanks,
Alessandro.
//-----------
template <class T,unsigned int N>
class A;
template <class T,unsigned int N>
class B;
template <class T,unsigned int N>
class A
{
public:
A(){;}
T c[N];
};
template <class T,unsigned int N>
class B
{
public:
B(){;}
operator const A<T,N> &(){return *(A<T,N> *)this;}
That's a reinterpret_cast.
Never use casts, and when you do anyway, use named casts.
In this case you're invoking Undefined Behavior, almost never a good idea.
T c[N];
};
template <class T,unsigned int N>
T sum(const A<T,N> &a)
{
T s(0);
for (unsigned int i=0;i<N;i++)
s+=a.c[i];
return s;
}
//int sum(A<int,4> a)
//{
// int s(0);
// for (unsigned int i=0;i<4;i++)
// s+=a.c[i];
// return s;
//}
int main()
{
A<int,4> a;
B<int,4> b;
sum(a);
sum(b);
Here the argument is B<int,4>. Matching of template arguments to
establish candidate functions does not involve any user-defined
conversions; it's exact match only. And there is no T and N that make
the actual argument of type B<int,4> match the formal argument of type
A<T,N>& exactly.
}
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?