我有一个模板类,我试图根据类中的类型名对其方法进行专门化。代码的框架如下:
template <typename C> class Instance {
protected:
C data;
public:
void populateData();
/* want to change the behavior of populateData() depending on C */
};
我如何实现上述目标?
最佳答案
我想这就是你想要的:
template <typename C> class Instance {
protected:
C data;
public:
void populateData();
/* want to change the behavior of populateData() depending on C */
};
template<>
void Instance<int>::populateData() {
// Do something when C is int
}
您可以将函数专门化为您想要的任何类型。
关于C++ 模板类,根据类型名改变类方法的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50932330/