C++ 如何定义模板类的模板成员函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11394832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:06:47  来源:igfitidea点击:

How to define a template member function of a template class

c++templates

提问by Paul R

Possible Duplicate:
How do I define a template function within a template class outside of the class definition?

可能的重复:
如何在类定义之外的模板类中定义模板函数?

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)'

and I've also tried every other syntax variation I can think of for the template version of Bar.

我还尝试了我能想到的所有其他语法变体,用于Bar.

回答by jrok

template<typename T>
template<typename T2>
void Foo<T>::Bar(const T2* t) 
{
     // stop tearing your hair out
}

回答by 111111

template <typename T>
template <typename T2> 
void Foo<T>::Bar(const T2 * t) {
    // ... this is where I'm tearing my hair out ...
}

Ugly isn't it.

丑是不是。