首页 > 解决方案 > C ++专门化单个成员函数

问题描述

类模板成员特化的问题。

我有一个简单的类,我想专门化一个成员函数。我正在这样做:

template <class T>
class Object
{
public:
    Object() {}

    void print() const
    {
        std::cout << "It's the template" << std::endl;
    }
    // ...
};

template<>
void Object<int>::print() const
{
    std::cout << "It's an int" << std::endl;
}

最终导致成员函数的多个定义的编译错误。

如果只有一个源文件包含标题,一切都很好。

如果两个文件包含标题,我会收到以下错误:

/home/marc/QtProjects/QtAsp-Service/build-aspservice-Desktop_Qt_5_15_0_GCC_64bit-Debug/../src/Asp/aspobject.h:34:Fehler:'Asp2::print()'的多重定义;main.o:/home/marc/QtProjects/QtAsp-Service/build-aspservice-Desktop_Qt_5_15_0_GCC_64bit-Debug/../src/Asp/aspobject.h:34:这里首先定义

这在一般情况下可能吗?如果是,有什么问题。

标签: c++templatestemplate-specialization

解决方案


您的方式是正确的,但完全专业化的成员不再是模板,因此不再隐式内联。

inline如果您将定义保留在标题中,或者拆分声明(在标题中)和定义(在 cpp 中),则必须添加。

template<>
inline void Object<int>::print()
{
    std::cout << "It's an int" << std::endl;
}

推荐阅读