简体   繁体   English

模板对象作为模板类的静态成员

[英]Template object as static member of the template class

Imagine the following template class (setter and getter for the member _t omitted): 想象以下模板类(省略了成员_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;
};

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 . 我可以很好地实例化此模板,但是链接器在静态成员对象NONE上给出了一个未解决的外部错误。

I would have assumed that when instantiating the template, the line static chain<T> NONE ; 我本来以为在实例化模板时,行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? 我的问题是:是否有可能实现所有目标?如果没有,在没有每个模板实例化之前都明确定义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: 就像在非模板类中一样,您仅在类定义内声明了NONE ,但仍然需要对其进行定义:

template<class T>
class chain
{
    // the same as your example
};

// Just add this
template <class T>
chain<T> chain<T>::NONE;
template < typename T >
chain<T> chain<T>::NONE;

should work 应该管用

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

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