* Fraser Ross:
struct C { C(int n) { printf("%d\n", n); } };
template<int N>
struct A {
static C c;
};
template<int N>
C A<N>::c(N);
A<2> a2;
A<1> a1;
int main() {
A<1>::c; A<2>::c;
}
I copied this from the moderated group. Why is it necessary to have the
given code in the main function to get an output from Cs constructor?
Is the compiler allowed to forego the creation of a1 and a2 since they
are not required for the program? I have tried this program with all
optimisations off and I still need the code in the constructor.
Consider the following code:
template< typename T >
struct X
{
void foo() { T().trallala(); }
void bar() {}
};
int main()
{
X<void>();
}
This should compile fine with any compiler, even though 'void' is not a class
type, and certainly is not one with a member function 'trallala'.
It's allowed because *if* class X is instantiated with T some class type with a
'trallala' member, then 'foo' can be used for that instantiation.
In short with a class template only what's used is instantiated (although if you
have syntax errors or other ordinary C++ errors such as zero-size array, or
refer to non-existing things that do not depend on a template parameter, then
compilation of the template itself will fail, before anything's instantiated).
At this point check to see if you can't make sense of the behavior you've
observed!
But there is a more subtle thing. With MSVC the output is 2,1, whereas with
MinGW g++ 3.4.5 the output is 1,2. I'm not quite sure what the standard has to
say about this, if anything, but it doesn't matter much because if you rely on
any specific order for such a subtle feature (dark corner of the language), then
you're doomed: the main rule is the stay away from those dark corners unless you
absolutely have to, because both compilers and other programmers get confused.
Cheers & hth.,
- Alf