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

Pau*_*l R 40 c++ templates

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

我正在努力解决模板类中模板成员函数的情况:

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 ...
}
Run Code Online (Sandbox Code Playgroud)

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

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)’
Run Code Online (Sandbox Code Playgroud)

我也尝试过我可以想到的模板版本的所有其他语法变体Bar.

jro*_*rok 96

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

  • 行`template <typename T>`和`template <typename T2>`可以改变位置吗? (2认同)
  • @hkBattousai如果你将`Foo <T>`改为`Foo <T2>`,那么是的.订单很重要. (2认同)

111*_*111 9

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

丑陋不是吗

  • 是的 - 令人惊讶的是,您可以尝试多少不同且看似合乎逻辑的语法变体而不会绊倒正确的语法变体. (4认同)
  • @PaulR老实说模板它变得如此纠结,我在类定义中编写实现.我真的相信这很容易阅读然后所有与模板垃圾添加到它分离出来. (3认同)
  • 是的 - 我开始看到这样做的吸引力。 (2认同)