模板类成员函数的显式特化

模板类成员函数的显式特化

问题描述:

我需要为某种类型专门化模板成员函数(比如double).虽然 X 类本身不是模板类,但它工作正常,但是当我将其设为模板时,GCC 开始给出编译时错误.

I need to specialize template member function for some type (let's say double). It works fine while class X itself is not a template class, but when I make it template GCC starts giving compile-time errors.

#include <iostream>
#include <cmath>

template <class C> class X
{
public:
   template <class T> void get_as();
};

template <class C>
void X<C>::get_as<double>()
{

}

int main()
{
   X<int> x;
   x.get_as();
}

这里是错误信息

source.cpp:11:27: error: template-id
  'get_as<double>' in declaration of primary template
source.cpp:11:6: error: prototype for
  'void X<C>::get_as()' does not match any in class 'X<C>'
source.cpp:7:35: error: candidate is:
  template<class C> template<class T> void X::get_as()

我该如何解决这个问题?这里有什么问题?

How can I fix that and what is the problem here?

提前致谢.

它不能那样工作.您需要说出以下内容,但它正确

It doesn't work that way. You would need to say the following, but it is not correct

template <class C> template<>
void X<C>::get_as<double>()
{

}

显式特殊成员需要将其周围的类模板显式特殊化以及.所以你需要说下面的话,这只会特化 X 的成员.

Explicitly specialized members need their surrounding class templates to be explicitly specialized as well. So you need to say the following, which would only specialize the member for X<int>.

template <> template<>
void X<int>::get_as<double>()
{

}

如果您想让周围的模板保持非专业化,您有多种选择.我更喜欢重载

If you want to keep the surrounding template unspecialized, you have several choices. I prefer overloads

template <class C> class X
{
   template<typename T> struct type { };

public:
   template <class T> void get_as() {
     get_as(type<T>());
   }

private:
   template<typename T> void get_as(type<T>) {

   }

   void get_as(type<double>) {

   }
};