简体   繁体   English

sizeof of template class

[英]sizeof of template class

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. 这段代码编译得很好(VS2010),但我怀疑(*)字符串。 S is not complete type, unlike S<N> in my opinion then how come the compiler knows its size? S不是完整的类型,不像S<N>在我看来那么编译器怎么知道它的大小? What does the standard say about such situation, does it well-formed correct sizeof ? 标准对这种情况说了什么,它是否形成了正确的sizeof

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 struct S定义中的名称S指的是注入的类名 S ,根据14.6.1 / 2(C ++ 03),它不需要显式的参数列表

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 <>. 在类模板特化或部分特化的范围内,当inject-name-name后面没有<时,它等同于inject-class-name,后跟类模板特化或部分特化的template-arguments。括在<>中。

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
    }
};

C++ implicitly inserts using S = S<N>; C ++ using S = S<N>;隐式插入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 . 如果你没有这将是一个错误sizeof(S)的定义之外S

Within a template, the template name is also the injected class name and refers to the class type S<N> rather than the template; 在模板中,模板名称也是注入的类名,并且引用类类型S<N>而不是模板; 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. 所以两者都是有效的,彼此相同。

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. 到那时,该类已经被实例化,编译器将拥有计算其大小所需的所有信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM