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?