【发布时间】:2017-08-22 10:53:58
【问题描述】:
按照@Jonas 在previous question 中的建议,我定义了一个模板化类来保存任意容器(字符串、树等)的任意容器(向量、集合、映射等)。到目前为止,我的定义是这样的:
template <template <typename...> class Container, typename Containee = std::string, typename... extras>
class Lemario
{
public:
typedef typename Container<Containee, extras...>::iterator iterator;
typedef typename Container<Containee, extras...>::const_iterator const_iterator;
// Use 'Containee' here (if needed) like sizeof(Containee)
// or have another member variable like: Containee& my_ref.
Container<Containee, extras ...> mTheContainer;
int loadContainees(const char *filename) {
Containee w, line;
// do some stuff here
}
void appendContainee(const Containee &__x);
};
现在,我可以在模板定义之外定义内联(如 loadContainees)方法。外面:
template <template <typename...> class Container, typename Containee, typename... extras>
Containee Lemario<Container, Containee, extras...>::transform_word(const Containee& word) const
{
Containee result;
return result;
}
到目前为止一切顺利。
但现在我想专门研究一种方法,将 Contaniee 附加到 Container 作为矢量、地图、树,使用不同的方法。所以我尝试专门化 std::vector:
template <template <typename...> class Container, typename Containee, typename... extras>
void Lemario<std::vector, Word>::appendContainee(const Word & word)
{
mTheContainer.push_back(word);
}
但我收到以下错误:
error: prototype for ‘void Lemario<std::vector, gong::Xtring>::appendContainee(const Word&)’ does not match any in class ‘Lemario<std::vector, gong::Xtring>’
除此之外,¿我可以只专门化 Container,std::vector,而让 Containee 不专门化吗?
template <template <typename...> class Container, typename Containee, typename... extras>
void Lemario<std::vector, Containee>::appendContainee(const Containee & word)
{
mTheContainer.push_back(word);
}
【问题讨论】:
-
如果我没记错的话,你不能将类模板中的函数与类本身分开来专门化
-
这是一个典型的 XY 问题。您上一个问题的正确答案是 Toby Speight。这里不需要这种复杂的结构。
-
错误
Word未定义。 -
对不起,我在 cpp.sh 上创建了一个脚本:cpp.sh/4pn4z
-
仅供参考,变量名
__x是reserved identifier,不要使用它。