declaration order of member variables in struct
Michael Eager
eager@eagercon.com
Sun Aug 2 02:49:00 GMT 2009
Martin Ettl wrote:
> Hello,
>
> i have following source, that compiles when the order of the declarations is as following:
>
> #include <iostream>
> #include <cstring>
>
> template <int N, int Low=1, int Upp=N> struct Root
> {
> static const int mean = (Low+Upp)/2;
> static const bool down = ((mean*mean)>=N);
> static const int ret = Root<N,(down?Low:mean+1),(down?mean:Upp)>::ret;
> };
> template <int N, int Mid> struct Root<N,Mid,Mid>
> {static const int ret = Mid;};
>
> int main()
> {
> std::cout << Root<10,1,10>::ret << std::endl;
> }
>
> But, when i reorder the declaration sequence in struct Root as followed:
>
> template <int N, int Low=1, int Upp=N> struct Root
> {
> static const int ret = Root<N,(down?Low:mean+1),(down?mean:Upp)>::ret;
^^^^ ^^^^ ^^^^ ^^^^
Neither down nor mean are defined before they are referenced.
> static const int mean = (Low+Upp)/2;
> static const bool down = ((mean*mean)>=N);
> };
>
> g++-4.4.1 complains about and prints the following output:
>
> ../src/TestRoot.cpp:8: error: ‘down’ was not declared in this scope
> ../src/TestRoot.cpp:8: error: ‘mean’ was not declared in this scope
> ../src/TestRoot.cpp:8: error: ‘down’ was not declared in this scope
> ../src/TestRoot.cpp:8: error: ‘mean’ was not declared in this scope
Two references to 'down' and two references to 'mean', not declared
before being used.
> ../src/TestRoot.cpp:8: error: template argument 2 is invalid
> ../src/TestRoot.cpp:8: error: template argument 3 is invalid
Arguments 2 and 3 contain undefined variables.
>
> I do not understand why this depends on the order of declaration?
Each symbol (variable or type) in C/C++ must be declared before it is used.
--
Michael Eager eager@eagercon.com
1960 Park Blvd., Palo Alto, CA 94306 650-325-8077
More information about the Gcc-help
mailing list