簡體   English   中英

成員函數的模板專業化

[英]Template Specialization for member functions

我最近發現了C ++中的template specialization

template <typename T>
void    fct(void) {}

template <>
void    fct<int>(void) {}

int main(void) {
  fct<int>();
  return 0;
}

我想對類中的成員函數使用模板專門化。

class   MyClass {
  public:
    template <typename T>
    static void fct(void) {}

    template <>
    static void   fct<int>(void) {}
};

int     main(void) {
  MyClass::fct<int>();

  return 0;
}

不幸的是,使用g++編譯會給我以下錯誤:

error: explicit specialization in non-namespace scope ‘struct MyClass’
error: template-id ‘toto<int>’ in declaration of primary template

我已經注意到,進行模板專門化可以在主作用域或名稱空間中工作,而不能在結構或類中工作。

我在stackoverflow上找到了一些有關使用命名空間的內容,例如以下代碼:

namespace myNameSpace {
  template <typename T>
  void fct(void) {}

  template <>
  void fct<int>(void) {}
}

class   MyClass {
  public:
    template <typename T>
    static void fct(void) {
      myNameSpace::fct<T>();
    }
};

int     main(void) {
  MyClass::fct<int>();

  return 0;
}

我究竟做錯了什么? 是否可以使用成員函數進行模板專業化? 如果不是,解決此問題的最佳方法是什么? 有沒有比使用名稱空間更好的方法呢?

在類定義之后編寫專長:

class MyClass
{
public:
    template <typename T>
    static void fct(void) {}
};

template <>
void MyClass::fct<int>() {}

暫無
暫無

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

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