我写了一个模板化的容器类 MyCont:
#include <iostream>
template <class T>
class MyCont
{
public:
void SomeFunc();
T* list;
};
template <class T>
void MyCont<T>::SomeFunc()
{
std::cout<<"in function"<<std::endl;
//...
}
int main()
{
MyCont<int> y;
y.SomeFunc();
MyCont< MyCont<int> > x;
x.SomeFunc();
}
这很好用。但是,如果 MyCont 的类型为 MyCont,我希望能够更改 SomeFunc() 的行为。 我不确定该怎么做(或者即使可能)。我试过在 SomeFunc() 的第一个定义下面添加这个:
template <>
void MyCont< MyCont<class T> >::SomeFunc()
{
std::cout<<"in altered function"<<std::endl;
//...
}
这会编译,但它总是第一个被调用的 SomeFunc
谢谢
最佳答案
这实际上是一种有趣的情况。我猜你是想写
template <class T>
void MyCont< MyCont<T> >::SomeFunc()
{
std::cout<<"in altered function"<<std::endl;
//...
}
编译失败。相反,你写了
template <>
void MyCont< MyCont<class T> >::SomeFunc()
{
std::cout<<"in altered function"<<std::endl;
//...
}
在你的类之外,所以放错地方的 class T
向前声明了一个类型 T
。这意味着编译器会为 MyCont
的特化生成一个函数,该函数不存在,因此不会被使用。
要明白我的意思,请在主模板之后添加以下特化:
template <class T>
struct MyCont< MyCont<T> > : MyCont<T>
{
void SomeFunc();
};
现在将与第一个固定版本一起调用。如果没有类(class)的特化,您将无法实现您的目标。
关于c++ - 为模板化容器类专门化成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19199260/