Re: Int-cast floating point expressions as constants?
Joel Yliluoma ha scritto:
I recently ran across this problem... My code looks like this.
#define SomeFloat 0.5
static const int SomeIntConst = ((int)(SomeFloat + 0.5));
template<int V>
struct SomeStruct
{
};
int main()
{
SomeStruct<SomeIntConst> ();
return 0;
}
When I compile this with ICC, or GCC, or Microsoft Visual C++,
with default settings, it compiles properly.
Even with GCC -ansi, it compiles properly.
They shouldn't. The standard says in 5.19/1:
"An integral constant-expression can involve only literals (2.13),
enumerators, const variables or static data members of integral or
enumeration types initialized with constant expressions (8.5), non-type
template parameters of integral or enumeration types, and sizeof
expressions. Floating literals (2.13.3) can appear only if they are cast
to integral or enumeration types."
In your case, after macro substitution the expression looks like
"((int)(0.5 + 0.5))" and there are two floating literals that are not
cast to integral types. This is not allowed. The fact that the sum of
the two literals is cast to int is totally irrelevant.
However, when I compile it with GCC's -pedantic option, I get
the following error messages:
tmp.cc:11: error: 'SomeIntConst' cannot appear in a constant-expression
tmp.cc:11: error: template argument 1 is invalid
What is the right behavior in this situation for a compiler to do?
The code is ill-formed, so the correct behaviour is to issue a diagnostic.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]