c++ - 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:这里首先定义
这在一般情况下可能吗?如果是,有什么问题。
解决方案
您的方式是正确的,但完全专业化的成员不再是模板,因此不再隐式内联。
inline
如果您将定义保留在标题中,或者拆分声明(在标题中)和定义(在 cpp 中),则必须添加。
template<>
inline void Object<int>::print()
{
std::cout << "It's an int" << std::endl;
}
推荐阅读
- javascript - 查看具有完美同步热图的树状图
- pandas - Polynomial Regression gives error "shapes (18,17) and (1140,1) not aligned: 17 (dim 1) != 1140 (dim 0)"
- serverless-framework - 文件中的无服务器引用变量不能使用两次
- excel - Check value for cell in Excel by VB
- git - Git Extensions stored wrong credentials
- python - Adding a comment to an element and making the element text appear after the comment
- javascript - Swift:有没有办法在 WKWebview 中使用本地 html 播放本地视频
- jquery - 如何将对象传递给popover fullcalendar
- axapta - 比较 AX2009 用户组权限
- android - Android 应用程序在棒棒糖及以下版本上滞后,主要在 Oppo、Vivo 和 MI 上运行,在模拟器上运行良好