gpt4 book ai didi

c++ - 另一个模板(同一类)的模板特化

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:25:34 24 4
gpt4 key购买 nike

我正在编写一个数组类。这个数组类可以再次包含数组作为成员。在实现打印功能时,我需要专门化。

26:template <class T> class array : public vector<T>{
public:
...
string* printToString();
...
};
...
template <class T> string* array<T>::printToString(){
... // generic function
}
template <> inline string* array<double>::printToString(){
... // spezialization for double, works
}
561:template <class U> string* array<array<U>*>::printToString(){
... // does not work
}

最后的定义产生

src/core/array.h:561: error: invalid use of incomplete type ‘class array<array<T> >’
src/core/array.h:26: error: declaration of ‘class array<array<T> >’

如果重要的话,g++ 版本是 g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3。有什么想法吗?

提前致谢,托马斯

最佳答案

作为 David 解决方案的替代方案,您可以无条件地将调用转发给一组重载函数:

template <class T> class array;
namespace details {
template <class T> std::string array_print(array<T> const&);
std::string array_print(array<double> const&); // Regular function
template <class T> std::string array_print(array<array<T> > const&);
}

template <class T> class array : private vector<T> {
public:
...
std::string printToString() { return details::array_print(*this); }
...
};

namespace details { /* implementions after class is defined */ }

关于c++ - 另一个模板(同一类)的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7268901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com