c++ - 基于整体类模板专门化一个类方法

标签 c++ templates template-specialization

如何专门化 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/

相关文章:

c++ - 将模板从类特化为整数

c++ - 指定类模板参数的要求

c++ - 通过引用 : TypeError: No to_python (by-value) converter found for C++ type: 调用 Boost.Python

database - 在模板中使用 Django 链 如何?

c++ - 如何在不创建对象实例的情况下强制创建模板代码?

c++ - 在函数模板的声明部分中定义时,对任意类型属性的函数重载失败

c++ - 获取模板类型的模板参数类型

c++ - 模板和显式特化

c++ - 选择要在运行时链接的库

c++ - 没有滚动条的cpp win7控制台