简体   繁体   English

模板类的默认参数会实例化模板吗?

[英]Does default argument of template class, instantiate the template?

Does the following default argument for the template instantiates a template with type EmptyClass ? 模板的以下默认参数是否实例化类型为EmptyClass的模板?

class EmptyClass{};

template <typename TYPE=EmptyClass>
class Sample
{
public:
    static void test()
    {
        TYPE::Serialize();
    }
};

No. Template are instantiated when used, and are instantiated on a per-function base. 否。模板在使用时被实例化,并基于每个功能实例化。

Default parameter values are just the types to use when the parameter is not specified. 默认参数值只是未指定参数时要使用的类型。 But does not themselves imply usage. 但是,它们本身并不暗示使用。

When you call Sample<>::test() then Sample<Emptyclass>::test() is instantiated and the EmptyClass::serialize() call attempted, resulting in a compile-time error (Since Emptyclass is declared as not having such function) 当您调用Sample<>::test()将实例化Sample<Emptyclass>::test()并尝试调用EmptyClass::serialize() ,从而导致编译时错误(因为Emptyclass被声明为不具有此类功能)

Try to make up more function, containing different compile-time errors referring to different parameter, and you'll see how, until the function is not used, no error is produced. 尝试组成更多函数,其中包含涉及不同参数的不同编译时错误,您将了解如何使用该函数,直到不使用该函数,才不会产生错误。

No, in that code any instance of EmptyClass is created. 不,在该代码中将创建EmptyClass的任何实例。 Serialize is a static function. 序列化是一个静态函数。 And EmptyClass's constructor is never called (in code showed) 而且从不调用EmptyClass的构造函数(在显示的代码中)

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

相关问题 当 function 模板参数是带有默认参数的 class 模板时,模板参数推导如何执行 - How does the template argument deduction perform for function template parameter when it is a class template with default argument 类模板参数推导和默认模板参数 - Class template argument deduction and default template parameters 隐藏在类默认模板参数后面的方法中的默认模板参数 - Default template argument in method hidden behind class default template argument 使用模板类的成员实例化MSVC ++中的模板默认参数 - Using member of template class to instantiate template default parameter in MSVC++ 模板中的模板默认参数 - template default argument in a template 模板类无法识别模板参数 - template class does not recnognize template argument 将具有默认模板参数的类模板作为具有较少参数的模板参数进行匹配 - Match class template with default template parameters as a template argument with fewer parameters 如何实例化模板类的模板 - how to instantiate a template of template class 具有不同默认模板参数和偏特化参数的 class 模板的分辨率 - Resolution of class template with different default template argument and partial specialization argument 模板类的模板参数 - template argument of template class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM