implicit cast in templated function

H

hweekuan

Hi,

I am trying to experiment with expression templates and come across
this issue of implicit cast for the arguments of templated functions,
below is the code and compile error. Why is the compiler not able to
cast? Thanks.

1 #include <iostream>
2
3 template<class U>
4 struct T {
5 T(U i) : b(i) { }
6 U b;
7 };
8 // ---------------------------
9 template<class A>
10 void print(T<A>& t,T<A>& y) {
11 std::cout<<__LINE__<<" "<<t.b<<std::endl;
12 }
13 // ---------------------------
14 int main ( ) {
15
16 T<int> t1(2),t2(4);
17
18 print(t1,3);
19 }
20 // ---------------------------

compile error
g++ -Wall u.C
u.C: In function ‘int main()’:
u.C:18: error: no matching function for call to ‘print(T<int>&, int)’

----------
g++ --version
i686-apple-darwin9-g++-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5465)
Copyright (C) 2005 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There
is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
 
O

olekk

Hi,

I am trying to experiment with expression templates and come across
this issue of implicit cast for the arguments of templated functions,
below is the code and compile error. Why is the compiler not able to
cast? Thanks.

1 #include <iostream>
2
3 template<class U>
4 struct T {
5 T(U i) : b(i) { }
6 U b;
7 };
8 // ---------------------------
9 template<class A>
10 void print(T<A>& t,T<A>& y) {
11 std::cout<<__LINE__<<" "<<t.b<<std::endl;
12 }
13 // ---------------------------
14 int main ( ) {
15
16 T<int> t1(2),t2(4);
17
18 print(t1,3);
19 }
20 // ---------------------------

compile error
u.C: In function �int main()�:
u.C:18: error: no matching function for call to �print(T<int>&, int)�

It's because the arguments for a class template can not be deduced
from the arguments of its constructor.

Regards
 
R

red floyd

It's because the arguments for a class template can not be deduced
from the arguments of its constructor.

And even if they could be deduced (which they can't), you wouldn't
match anyways, because you wouldn't be able to bind the temporary to
the reference for the second param.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,708
Latest member
SherleneF1

Latest Threads

Top