本文介绍了如何定义模板类的模板成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在模板类中具有模板成员函数的情况下,我在语法上苦苦挣扎:
I'm struggling with the syntax for the case where I have a template member function within a template class:
template <typename T> class Foo
{
void Bar(const T * t);
template <typename T2> void Bar(const T2 * t);
};
template <typename T> void Foo<T>::Bar(const T * t)
{
// ... no problem ...
}
template <typename T> void Foo<T>::Bar<typename T2>(const T2 * t)
{
// ... this is where I'm tearing my hair out ...
}
第一个成员函数很好,但是处理模板类的基本类型以外的类型的模板成员函数是我遇到问题的地方.对于上述情况,我得到以下错误:
The first member function is fine, but the template member function which handles types other than the base type of the template class is where I am having problems. For the above case I get the following errors:
template_problem.cpp:12: error: parse error in template argument list
template_problem.cpp:12: error: expected ‘,’ or ‘...’ before ‘*’ token
template_problem.cpp:12: error: ISO C++ forbids declaration of ‘T2’ with no type
template_problem.cpp:12: error: template-id ‘Bar<<expression error> >’ in declaration of primary template
template_problem.cpp:12: error: prototype for ‘void Foo<T>::Bar(int)’ does not match any in class ‘Foo<T>’
template_problem.cpp:4: error: candidates are: template<class T> template<class T2> void Foo::Bar(const T2*)
template_problem.cpp:7: error: void Foo<T>::Bar(const T*)
template_problem.cpp:12: error: template definition of non-template ‘void Foo<T>::Bar(int)’
,而且我还尝试了 Bar
的模板版本可以想到的所有其他语法变体.
and I've also tried every other syntax variation I can think of for the template version of Bar
.
推荐答案
template<typename T>
template<typename T2>
void Foo<T>::Bar(const T2* t)
{
// stop tearing your hair out
}
这篇关于如何定义模板类的模板成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!