簡體   English   中英

模板對象作為模板類的靜態成員

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

想象以下模板類(省略了成員_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;
};

這個概念的基本思想是,我沒有使用空指針,而是擁有一個靜態的默認元素,該元素在保持技術上有效的同時擔當了這個角色。 這可以防止空指針的某些問題,同時使代碼更冗長...

我可以很好地實例化此模板,但是鏈接器在靜態成員對象NONE上給出了一個未解決的外部錯誤。

我本來以為在實例化模板時,行static chain<T> NONE ; 它實際上也將是一個定義,因為它實際上發生在實例化模板的實現中。 然而,事實證明不是...

我的問題是:是否有可能實現所有目標?如果沒有,在沒有每個模板實例化之前都明確定義NONE元素的情況下,如何實現?

您仍然需要像非模板類一樣在類外部定義它。 就像在非模板類中一樣,您僅在類定義內聲明了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;

應該管用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM