簡體   English   中英

模板類的靜態模板成員函數

[英]Static template member function for template class

我有一個模板類和一個模板成員函數:

template<class T1>
struct A{
    template<class T2>
    static int f(){return 0;}
};

我想專攻T1T2相同的情況,

例如,為任何T定義 case A<T>::f<T>

但我找不到關鍵字組合來實現這一點。

我如何部分(?)專門化模板類和模板靜態函數的組合?


這些是我失敗的嘗試,以及錯誤消息:

1) 在類fatal error: cannot specialize a function 'f' within class scopefatal error: cannot specialize a function 'f' within class scope

template<class T1>
struct A{
    template<class T2>
    static int f(){return 0;}

    template<>
    static int f<T1>(){return 1;}

};

2) 在類外“同時”特化: fatal error: cannot specialize a member of an unspecialized template

template<class T>
void A<T>::f<T>(){return 1;}

3) 專門使用template<>fatal error: too few template parameters in template redeclaration

template<> template<class T>
void A<T>::f<T>(){return 1;}

4) 顛倒順序: fatal error: cannot specialize (with 'template<>') a member of an unspecialized template

template<class T> template<>
void A<T>::f<T>(){return 1;}

5)特化整個類(基於嘗試3的錯誤): fatal error: class template partial specialization does not specialize any template argument; to define the primary template, remove the template argument list fatal error: class template partial specialization does not specialize any template argument; to define the primary template, remove the template argument list

template<class T> 
struct A<T>{
    template<>
    static int f<T>(){return 1;}
};

6)特化類而不特化函數(?): fatal error: too few template parameters in template redeclaration template<> template<class T1>

template<> template<class T>
int A<T>::f(){return 0;}

我使用了clang 3.5 C++14來生成錯誤消息。

你不能部分特化一個函數。

您可以將工作轉發到另一種類型:

template<class T1>
struct A;

template<class T1, class T2>
struct A_helper {
  static int f() {
    return A<T1>::f_simple<T2>();
  }
};
template<class T>
struct A_helper<T,T> {
  static int f() {
    return A<T>::f_special();
  }
};

template<class T1>
struct A{
  template<class T2>
  static int f(){return A_helper<T1,T2>::f()}
  template<class T2>
  static int f_simple(){return 0;}
  static int f_special(){return -1;}
};

或者,更簡單地說,沒有A_helper

template<class T1>
struct A{
  template<class T2>
  static int f(){return f2<T2>(std::is_same<T1,T2>{});}
  template<class T2>
  static int f2(std::true_type){
    static_assert(std::is_same<T1,T2>{}, "bob!");
    return -1;
  }
  template<class T2>
  static int f2(std::false_type){return -1;}
};

您可以使用標簽調度。

另一種方法:

template<class T>struct tag{};

template<class T1>
struct A{
  template<class T2>
  static int f(){return f2(tag<T2>{});}
  template<class T2>
  static int f2(tag<T2>) {return 0;}
  static int f2(tag<T1>) {return -1;}
};

我們直接調度T2的類型。

暫無
暫無

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

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