模板对象作为模板类的静态成员
想象一下下面的模板类(省略了成员_t
的setter和getter):
template<class T>
class chain
{
public:
static chain<T> NONE;
chain()
: _next(&NONE)
{}
~chain() {}
chain<T>& getNext() const
{
return *_next;
}
void setNext(chain<T>* next)
{
if(next && next != this)
_next = next;
}
chain<T>& getLast() const
{
if (_next == &NONE)
return *this;
else
return _next->getLast();
}
private:
T _t;
chain<T>* _next;
};
这个概念的基本思想是,我不使用空指针,而是有一个静态默认元素来承担这个角色,而仍然是技术上有效的对象;这可以防止空指针的一些问题,同时使代码更加冗长...
我可以很好地实例化此模板,但链接器在静态上给出了 unresolved-external 错误成员对象NONE
。
我假设在实例化模板时,行 static chain
;实际上也将是一个定义,因为它实际上发生在实例化模板的实现中。然而,事实证明并非如此......
我的问题是:是否有可能,如果可以,如何在每个模板实例化之前不显式定义 NONE
元素?
Imagine the following template class (setter and getter for the member _t
omitted):
template<class T>
class chain
{
public:
static chain<T> NONE;
chain()
: _next(&NONE)
{}
~chain() {}
chain<T>& getNext() const
{
return *_next;
}
void setNext(chain<T>* next)
{
if(next && next != this)
_next = next;
}
chain<T>& getLast() const
{
if (_next == &NONE)
return *this;
else
return _next->getLast();
}
private:
T _t;
chain<T>* _next;
};
The basic idea of this concept is, instead of using null-pointers, I have a static default element that takes in this role while still being a technically valid object; this could prevent some of the issues with null pointers while making the code more verbose at the same time...
I can instantiate this template just fine, but the linker gives an unresolved-external error on the static member object NONE
.
I would have assumed that when instantiating the template, the line static chain<T> NONE
; would effectively be a definition, too, as it actually happens within the implementation instantiating the template. However, it turns out not to be...
My question is: is something like possible at all, and if so, how, without explicitly defining the NONE
element before each and every template instantiation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您仍然需要像非模板类一样在类外部定义它。就像在非模板类中一样,您只在类定义中声明了
NONE
并且仍然需要定义它:You still need to define that outside the class just like a non-template class. Just like in a non-template class, you have only declared
NONE
inside the class definition and still need to define it:应该有效
should work