gpt4 book ai didi

C++ 模板和静态成员 - header 中的定义

转载 作者:可可西里 更新时间:2023-11-01 16:34:42 26 4
gpt4 key购买 nike

考虑以下构造:

//! Templated singleton.
/*!
Template wrapper enforcing the singleton behavior.
*/
template <class T>
class TSingleton
{
private:
//! Singleton instance pointer.
static T* instance;
//! private constructor.
TSingleton() { }
//! private empty copy constructor.
TSingleton(const TSingleton<T>& sourceObject) {}

public:
//! Static singleton instance getter.
static T* GetInstance()
{
if (instance == 0)
instance = new T();
return instance;
}

};

template <class T> T* TSingleton<T>::instance = 0;

这个模板类和静态实例的定义写在同一个头文件中。对于非模板类,这由于为实例静态成员定义了多个符号而导致链接时错误。对于模板来说,这似乎也很直观,因此必须将定义分开并将其放入 .cpp 文件中。但是模板通常是在类似头文件的文件中声明和定义的。 是什么让这种语法对模板类有效和起作用?

有一个wikipedia链接,但它没有提供关于模板类情况下会发生什么的明确解释。

最佳答案

这是有效的,因为 [basic.def.odr]/5 明确允许复制模板:

There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template parameters are not specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. ...

要求很长,所以我不会在这里重复它们,但基本上它们声明每个重复的定义必须相同(否则程序有未定义的行为)。

关于C++ 模板和静态成员 - header 中的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12214112/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com