Why does this template code compile?
Hello,
I was expecting this code to stop with a syntax error, or at least give a warning that I am calling an int32_t function with an int64_t argument, and yet it compiles silently:
sun02% cat templ.cpp
[code]#include <stdio.h>
#include <inttypes.h>
template<class Y> class keylookup
{
public:
void print_all_codes(Y arg)
{
printf("Doing it! sizeof(Y)==%d\n",sizeof(Y));
}
};
int main()
{
keylookup<int32_t> kl;
int64_t batty=6;
kl.print_all_codes(batty);
}[/code]
sun02% CC -V
CC: Sun C++ 5.8 Patch 121017-02 2006/04/19
sun02% CC -o templ templ.cpp
sun02% templ
Doing it! sizeof(Y)==4
sun02%
Possibly this is a C++ Standards question since the same thing happens with g++ and IBM's xlC_r.
-- Steve
[889 byte] By [
sjgilbertz] at [2007-11-26 8:06:11]

# 1
If we take templates out of the picture, your code is equivalent to this: [code]
void print_all_codes(int arg) { ... }
int main()
{
long long value = 6; // int64_t is long long
print_all_codes(value);
} [/code]
Any integer value can be converted to any other integer type. If the value cannot be represented in the new type, the conversion is done modulo the size of the new type if the type is unsigned. Otherwise, the results are undefined. Reference: C++ Standard, section 4.7 "Integral conversions"
Using Sun C++, you can add the option +w for addtional compiler warnings. You will then get a warning about conversions that might cause truncation.
# 3
The result is undefined only if the value won't fit.
Common programming techniques involve mixing int and char types for character I/O. The stdio functions use int almost everywhere for characters. It would be extremely annoying to get a warning for every instance of storing a character held in an int variable into a char variable. [code]
char* p = ...;
int c;
for(int i=0; c=getchar() && c != EOF; ++i)
*p++ = c; // warning here, although the code is safe
[/code]
# 5
I'm not sure I understand you. If you get a warning about a conversion that you know is both safe and what you want, you will be tempted to insert a cast to eliminate the warning.
Casts are usually a Bad Idea, except in limited situations where you want to flag non-portable code. If data types change, the cast you inserted to prevent warnings could become inappropriate, leading to strange program behavior.
Other compilers might differ, but we chose to have our compiler warn about possible truncation only if you ask for the warning.