13
template<int N>
struct S
{
    void foo()
    {
        sizeof( S ); // (*)
        sizeof( S<N> );
    }
};

int main()
{
    S<5> s;
    s.foo();
    return 0;
}

This code compiles fine (VS2010), but i have doubts about (*) string. S is not complete type, unlike S<N> in my opinion then how come the compiler knows its size? What does the standard say about such situation, does it well-formed correct sizeof?

4

4 回答 4

15

Name S inside the definition of struct S refers to the injected class name S, which according to 14.6.1/2 (C++03) does not require an explicit argument list

Within the scope of a class template specialization or partial specialization, when the injected-class-name is not followed by a <, it is equivalent to the injected-class-name followed by the template-arguments of the class template specialization or partial specialization enclosed in <>.

Note that if you deliberately force the compiler to use the "original" name of the template (instead of the injected class name) by using scope resolution operator, the parameter list will become mandatory

template<int N>
struct S
{
    void foo()
    {
        sizeof( ::S );    // <- ERROR
        sizeof( ::S<N> ); // <- OK
    }
};
于 2013-11-07T08:54:13.817 回答
11

C++ implicitly inserts using S = S<N>; into the class body, so the two statements are equivalent.

template<int N>
struct S {
    static_assert(std::is_same<S, S<N>>(), "");
};

It would be an error if you did sizeof(S) outside of the definition of S.

于 2013-11-07T08:45:54.553 回答
3

Within a template, the template name is also the injected class name and refers to the class type S<N> rather than the template; and within a class member function, the class type is complete even if the function is defined inside the class. So both are valid and equivalent to each other.

于 2013-11-07T08:49:34.573 回答
1

Member functions of class templates are not instantiated until they are called. By that time, the class will already be instantiated and the compiler will have all the information it needs to calculate its size.

于 2013-11-07T08:52:48.830 回答