Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

(learning) Two types in template but using only one?

14 views
Skip to first unread message

Christiano

unread,
Jan 26, 2017, 5:46:49 PM1/26/17
to
See the following program:

==== a.cpp ===========
#include "std_lib_facilities.h"

int main(void)
try {
int x1 = narrow_cast<int>(2.9);

return 0;
}
catch(exception &e) {
cerr << "**** ERROR: " << e.what() << "\n";
keep_window_open();

return 1;
}
=== end a.cpp ========

Running it:
debian@debian:~/principles$ ./a.out
**** ERROR: info loss
Press enter a character to exit
q
debian@debian:~/principles$

The narrow_cast definition uses TWO template types but it is used with only one ==> narrow_cast<int>(2.9);

narrow_cast here:
http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h

template<class R, class A> R narrow_cast(const A& a)
{
R r = R(a);
if (A(r)!=a) error(string("info loss"));
return r;
}

So, Why does it work when there are two types in template definition and just use one? Does It automatically identify the second type reading the argument type?

Marc Beauchesne

unread,
Jan 26, 2017, 9:21:04 PM1/26/17
to
It's using Template Argument Deduction. In this case, you specify R, but A is deduced from the type you supply as an argument. You can read more about it in the link below or in your favorite reference manual.

http://en.cppreference.com/w/cpp/language/template_argument_deduction

Alf P. Steinbach

unread,
Jan 26, 2017, 9:51:32 PM1/26/17
to
On 27.01.2017 03:20, Marc Beauchesne wrote:
> It's using Template Argument Deduction. In this case, you specify R, but A is deduced from the type you supply as an argument. You can read more about it in the link below or in your favorite reference manual.
>
> http://en.cppreference.com/w/cpp/language/template_argument_deduction
>
>
> On Friday, January 27, 2017 at 6:46:49 AM UTC+8, Christiano wrote:
>> See the following program:
>>
>> ==== a.cpp ===========
>> #include "std_lib_facilities.h"
>>
>> int main(void)
[snip]

Please don't top-post.

It's often a good idea to read the FAQ before posting; see <url:
http://www.dietmar-kuehl.de/mirror/c++-faq/how-to-post.html#faq-5.4>.

However, when the FAQ was migrated to isocpp.org/faq it became a general
C++ FAQ, and the netiquette stuff for this group was removed. But it's
still there in the countless mirrors of the original FAQ. Including
Dietmar's, linked to above (Dietmar Kuehl was one of the moderators of
clc++m.)


Cheers & hth.,

- Alf

0 new messages