New to C++ and learning from books so I can be quite pedantic or miopic in my reasoning.
In the case of template functions, I have read that when a parameter is passed by Reference, only conversions from Reference / Pointer to NonConst to Reference / Pointer to Const are alllowed.
That means I believe that
template <typename T> int compare(T&, T&);
should fail when calling compare(ci1, ci1), with ci1 being consntant int, as conversions from Const to NonCost are not allowed for Reference parameters.
However it works in my compiler (Visual C++ 10). Can someone explain me what I get wrong?
template <typename T> int compare(T&, T&);
template <typename T> int compare(T &v1, T &v2)
{
// as before
cout << "compare(T, T)" << endl;
if (v1 < v2) return -1;
if (v2 < v1) return 1;
return 0;
}
const int ci1 = 10;
const int ci2 = 20;
int i1 = 10;
int i2 = 20;
compare(ci1, ci1);
compare(i1, i1);
The call
compare( ci1, ci1 );
yields T as type const int (in your preferred notation).
The effective function signature is then
int compare( int const&, int const& )
You can use typeid(x).name() the check out what types you actually have.
Note: with g++ that yields some ungrokkable short forms, which you then need to use a special g++-specific runtime lib function to decode.
Cheers & hth.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With