How to define a template member function of a template class

C++Templates

C++ Problem Overview


> 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 forvoid 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.

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaul RView Question on Stackoverflow
Solution 1 - C++jrokView Answer on Stackoverflow
Solution 2 - C++111111View Answer on Stackoverflow