XCode 警告“此处需要实例化变量 'Singleton<Foo>::_instance',但没有可用的定义
XCode warns "Instantiation of variable 'Singleton<Foo>::_instance' required here but no definition is available
遗留代码库具有这种构造:
template< typename T >
class Singleton {
private:
static T* _instance;
public:
inline static T& instance() {
if (_instance == 0) { // warning here
_instance = new T;
}
return *_instance;
}
};
通常这样使用:
class Foo : public Singleton<Foo>
{
};
警告是从任何包含 Foo.hh
.
的文件生成的
目前,Foo.cpp
确实包括这一行:
template<>
Foo* Singleton<Foo>::_instance = nullptr;
但对编译没有帮助。有没有办法在定义 Foo 之前提供 Singleton::_instance 的定义?
XCode 9.2 Mac OS X 10.12.6
在你的头文件中,添加
template <typename T> T* Singleton<T>::_instance = nullptr;
这仍然是一个外联定义,但不依赖于特定的专业化。然后你应该能够删除行
template<> Foo* Singleton<Foo>::_instance = nullptr;
因为上面的非专门定义已经对所有实例化做了同样的事情。
遗留代码库具有这种构造:
template< typename T >
class Singleton {
private:
static T* _instance;
public:
inline static T& instance() {
if (_instance == 0) { // warning here
_instance = new T;
}
return *_instance;
}
};
通常这样使用:
class Foo : public Singleton<Foo>
{
};
警告是从任何包含 Foo.hh
.
目前,Foo.cpp
确实包括这一行:
template<>
Foo* Singleton<Foo>::_instance = nullptr;
但对编译没有帮助。有没有办法在定义 Foo 之前提供 Singleton::_instance 的定义?
XCode 9.2 Mac OS X 10.12.6
在你的头文件中,添加
template <typename T> T* Singleton<T>::_instance = nullptr;
这仍然是一个外联定义,但不依赖于特定的专业化。然后你应该能够删除行
template<> Foo* Singleton<Foo>::_instance = nullptr;
因为上面的非专门定义已经对所有实例化做了同样的事情。