如何定义一个模板类的模板成员函数

55

我正在为模板类中有一个模板成员函数的语法而苦恼:

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

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

第一个成员函数很好,但是处理模板类基本类型以外的类型的模板成员函数是我遇到问题的地方。对于上述情况,我收到以下错误信息:

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模板版本的所有语法变化。

2个回答

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

3
template<typename T>template<typename T2>这两行可以交换位置吗? - hkBattousai
5
如果你将 Foo<T> 改成 Foo<T2>,那么顺序就很重要。 - jrok
为什么需要将类模板函数定义为void Foo<T>::Bar(),而不是void Foo::Bar()?为什么要在Foo(类名)中添加<T>?为什么不是简单的Foo(类名)? - r18ul
@Rahul 因为它是一个模板类,需要一个模板参数。 - Qwerty01

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

很丑陋,不是吗。


9
是的 - 令人惊奇的是,你可以尝试许多不同的、看似合乎逻辑的句法变化,却仍无法找到正确的一种。 - Paul R
7
说实话,对于模板,它变得非常混乱,以至于我直接在类定义中编写实现。我坚信这比将所有内容分开并添加到模板垃圾中更容易阅读。 - 111111
2
是的 - 我开始意识到这样做的吸引力。 - Paul R

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接