简体   繁体   English

成员函数的模板专业化

[英]Template Specialization for member functions

I've recently discovered template specialization in C++. 我最近发现了C ++中的template specialization

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

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

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

I'd like to use template specialization for member functions inside a class. 我想对类中的成员函数使用模板专门化。

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

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

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

  return 0;
}

Unfortunately, compiling with g++ gives me the following error: 不幸的是,使用g++编译会给我以下错误:

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

I've noticed that doing template specialization works in main scope or in a namespace but not in a struct or in a class. 我已经注意到,进行模板专门化可以在主作用域或名称空间中工作,而不能在结构或类中工作。

I've found something on stackoverflow about using a namespace like in the following code: 我在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;
}

What am I doing wrong? 我究竟做错了什么? Is it possible to make template specialization with member functions? 是否可以使用成员函数进行模板专业化? If not, what is the best way to get around this? 如果不是,解决此问题的最佳方法是什么? Is there a better way than using namespace to get around this? 有没有比使用名称空间更好的方法呢?

Write the specialization after the class definition: 在类定义之后编写专长:

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