Re: template functions intricacies
On 27 Jun., 00:40, "mikel...@gmail.com" <mikel...@gmail.com> wrote:
[..]
if I change line /*1*/ making the template function call explicit
g<M,N>((*this).v,c.v);
everything works fine. so
1) I can't understand this behaviour
The problem is, that the compiler cannot deduce the template
arguments T and U from a call to g without explicit specification
of the template argument types in this case.
The reason is, that in C++ you can simply specialize every template
in a more or less arbitrary manner. Someone could simply specialize
foo in the following way:
template <>
class foo<int> {
public:
class val { public: double p; }; // Note: double, *not* int!
// .. remaining parts
};
or more worse, the specialization might not have *any* inner class
val at all:
template <>
class foo<float> {};
For this reason can a compiler never deduce from a template
typedef back to the template parameter. A possible workaround
would be to write g as follows:
template <class T, class U>
void g(T& a, U& b)
{ std::cout << a.p<<","<<b.p<<"\n"; }
This might be unsatisfactory for you, because T and U are
unconstrained, but the point is, that the same applies for
foo<T>::val compared to foo<U>::val for every T different
from U.
A cleaner solution would be to separate the inner class
from the outer one:
template <class M>
class val { public: M p; };
template <class M>
class foo {
public:
val<M> v;
template <class N> void h(foo<N>& c);
};
template <class T, class U>
void g(val<T>& a, val<U>& b)
{ std::cout << a.p<<","<<b.p<<"\n"; }
Now the compiler can deduce T and U from the
following (unchanged) call to g.
Greetings from Bremen,
Daniel Kr?gler
---
[ 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://www.comeaucomputing.com/csc/faq.html ]