簡體   English   中英

在 class 聲明之外實現的 enable_if 方法特化

[英]enable_if method specialization with implementation outside of class declaration

我正在編寫一個模板化的 singleton 超類,它可以提供線程本地實例或進程全局實例。 下面的代碼編譯並在技術上符合我的需要。 但是,如何在 class 聲明之外編寫 function 實現? 如何在 class 中聲明 function (注釋行是否正確)?

所有類似的問題都在 class 聲明中實現 function。

#include <vector>
#include <type_traits>


using namespace std;

template <class t, bool tls=true>
class A{
public:
  typedef std::vector<t> Avector;
//  static Avector& getVector();

  template <class T=t, bool TLS=tls, typename std::enable_if<!TLS>::type* = nullptr>
  static Avector&
  getVector(){
    static Avector v=Avector();
    return v;
  }

  template <class T=t, bool TLS=tls, typename std::enable_if<TLS>::type* = nullptr>
  static Avector&
  getVector(){
    static thread_local Avector v=Avector();
    return v;
  }
};

int main(){
  vector<int>& vi = A<int>::getVector();
  vector<double>& vd = A<double, false>::getVector();
  return 0;
}

你可以改為寫

template<typename T, bool>
struct A
{
    typedef std::vector<T> Avector;
    static Avector& getVector();
};

template<typename T, bool b>
typename A<T, b>::Avector& A<T, b>::getVector()
{
    thread_local typename A<T, true>::Avector v;
    return v;
}

template<typename T>
class A<T, false>
{
    typedef std::vector<T> Avector;
    static Avector& getVector();
};

template<typename T>
typename A<T, false>::Avector&  A<T, false>::getVector()
{
    static typename A<T, false>::Avector v;
    return v;
}

此外,通常不應使用單例

我正在尋找答案,在您發布問題 2 年后,我們在 Stack Overflow 上找到了答案: How to use std::enable_if on method of templated class with separate declaration and definition via specialization

  1. 首先,您必須將方法重新定義為模板,使用另一個類型名,並使用類模板的默認值。
  2. 其次,您必須在實現方面template<> 2 次。
// hpp
template<typename T>
class A {
    template <class U=T, typename std::enable_if_t<myCondition, bool>>
    void myMethod();
}
// cpp
template<typename T>
template <class U=T, typename std::enable_if_t<myCondition, bool>>
void A::myMethod() {
    // ...
}

如果您不想定義另一個模板參數,您可以將限制定義為返回類型。 在這里,我們將 bool 更改為 void,但它可以是任何你想要的:

// hpp
template<typename T>
class A {
    typename std::enable_if_t<myCondition, void>
    myMethod();
}
// cpp
template<typename T>
typename std::enable_if_t<myCondition, void>
A::myMethod() {
    // ...
}

暫無
暫無

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

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