类模板成员函数的专用化
Specialization of member function of class template
我有一个Base
类,我把它用作树。从这个基类中,我派生了一个模板Container
类,它应该能够容纳各种类型。我想给 Container 类一个toString
函数,该函数将其值及其所有子项的值转换为字符串。Container<A>
可以有不同类型的子Container<B>
。
我不知道该怎么做。下面是我的代码。
// File base.h:
class Base {
public:
virtual string toString();
protected:
vector<Base *> _children
}
// File base.cpp:
string Base::toString() {
string a="something"
return a;
}
然后我有一个模板化的派生类:
// File container.h:
template<class T>
class Container: public Base {
public:
string toString() override;
private:
T _data;
}
我想专门化 toString 函数,这样它就可以处理 不同类型:
File container.cpp:
template <class T>
string Container<T>::toString() {
string valueString = "not sure how to handle this type";
for(int i=0;i<_children.size;i++) {
valueString+=" "+_children[i]->toString();
}
return valueString;
}
template <>
string Container<int>::toString() {
string valueString = std::to_string(_data);
for(int i=0;i<_children.size;i++) {
valueString+=" "+_children[i]->toString();
}
return valueString;
}
我也为Base
类提供了一个toString
函数,因为我不知道如何将_children
强制转换为未指定的 Container 类,以便我可以访问其toString
函数。
如果我使用上述方法,则在链接时出现错误:
undefined reference to Container<void*>::toString()
undefined reference to Container<bool*>::toString()
以及我曾经使用过的所有其他类型。但是,我想避免专门化所有可能的类型。
编辑: 正如建议将容器的内容.cpp移动到头文件: 如果我这样做,我会收到这样的错误:
Multiple definition of Container<int>::toString().
First defined here
似乎基本上,无论我包括在哪里Container.h
我都会得到如此多重的定义。这虽然我有一个
#ifndef CONTAINER
#define CONTAINER
包括守卫?
C++模板仅在替换时编译。
在您的情况下,Container<T>::toString
在 sidecontainer.cpp
中定义,但没有替换,因此不会编译它们。
当你引用Container<T>::toString
某处时,函数的定义对编译单元不可见,编译将生成一个重定位槽,希望在链接阶段找到定义。但是该函数从未在任何地方定义过,因此您遇到了链接错误。
解决方案:将函数定义放在头文件中。
这里有一些更详细的解释。
相关文章:
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- 具有常量引用参数的函数模板专用化
- 在 C++20 中是否不再允许在 std 中对程序定义类型的函数模板进行专用化?
- C++模板专用化 - 无法匹配函数定义
- 具有专用化的模板类中的可靠条件复制和移动构造函数
- 如何使专用函数模板成为某个类的朋友?
- 如何按类型为元组元素创建专用函数
- 无法访问专用函数
- 使用指向部分专用函数成员的指针自动填充向量
- 64 位 G++ 4.6.3 不会在专用函数模板中将长整型视为长整型,即使它们的大小相同。这是一个错误吗?
- 操作员过载的专用函数
- C++调用模板专用函数
- 模板类中专用函数的声明
- 使用专用函数对异构集合的 STL 算法
- C++专用函数-不在此范围内错误
- 为什么我不能专用函数模板?
- 用于专用函数参数的模板
- 代码重复和模板专用化(当专用函数具有不同的返回类型时)
- 具有专用函数的Pull-Apart函数类型
- 专用函数模板