如何专门化 initialize()
(见下文),其中类型不是基于方法参数,而是基于整个类模板参数?
template<class STREAM_TYPE>
class MyClass
{
struct MyStruct
{
STREAM_TYPE* _ifs{nullptr};
}
public:
// Use this when STREAM_TYPE = std::ifstream
void initialize()
{
for(MyStruct& ms : _myStructs)
{
ms._ifs = new std::ifstream("");
}
}
// Use this when STREAM_TYPE = std::stringstream
void initialize()
{
}
private:
std::array<MyStruct, 10> _myStructs;
};
最佳答案
类模板的非模板成员本身就是独立的模板。您可以独立地专门化它们。在你的情况下 - 通过使用显式特化
// Main template
template<class STREAM_TYPE>
class MyClass
{
void initialize()
{
}
};
// Specialization, declared outside the main template definition
template<>
void MyClass<std::ifstream>::initialize()
{
for(MyStruct& ms : _myStructs)
{
ms._ifs = new std::ifstream("");
}
}
由您决定该方法的哪个版本是“默认”版本,哪个版本是“专用”版本。或者您可能想将这两个版本声明为特化。
例如,您可能决定将两个版本视为特化,同时将主版本定义为已删除
// Main template
template<class STREAM_TYPE>
class MyClass
{
void initialize() = delete;
};
// Specialization, declared outside the main template definition
template<>
void MyClass<std::ifstream>::initialize()
{
for(MyStruct& ms : _myStructs)
{
ms._ifs = new std::ifstream("");
}
}
template<>
void MyClass<std::stringstream>::initialize()
{
}
请记住,显式特化不再是模板。它作为普通函数遵守 ODR。即使您的模板类是在头文件中定义的(通常是模板类),上述特化的定义也必须转到 .cpp
文件。头文件应仅包含您的特化的声明
// header file declarations
template<> void MyClass<std::ifstream>::initialize();
template<> void MyClass<std::stringstream>::initialize();
而定义应保存在 .cpp
文件中。
关于c++ - 基于整体类模板专门化一个类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54380509/