我需要为某种类型专门化模板成员函数(比如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>) {
}
};
这篇关于模板类成员函数的显式特化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
std::reference_wrapper 和简单指针的区别?Difference between std::reference_wrapper and simple pointer?(std::reference_wrapper 和简单指针的区别?)
常量之间的区别.指针和引用?Difference between const. pointer and reference?(常量之间的区别.指针和引用?)
c++ - 如何从指向向量的指针访问向量的内容?How to access the contents of a vector from a pointer to the vector in C++?(c++ - 如何从指向向量的指针访问向量的内容?)
*& 的含义和**&在 C++ 中Meaning of *amp; and **amp; in C++(*amp; 的含义和**amp;在 C++ 中)
为什么我不能对普通变量进行多态?Why can#39;t I do polymorphism with normal variables?(为什么我不能对普通变量进行多态?)
取消引用已删除的指针总是会导致访问冲突?Dereferencing deleted pointers always result in an Access Violation?(取消引用已删除的指针总是会导致访问冲突?)