【发布时间】:2010-04-28 12:52:05
【问题描述】:
我有一个 MyClass 类,它以类型名 T 为模板。但在内部,我想要一个以另一种类型 TT(与 T 无关)为模板的方法。
阅读/修改后,我发现了以下符号:
template <typename T>
class MyClass
{
public :
template<typename TT>
void MyMethod(const TT & param) ;
} ;
出于文体原因(我喜欢将模板化的类声明放在一个头文件中,将方法定义放在另一个头文件中),我不会在类声明中定义方法。所以,我必须把它写成:
template <typename T> // this is the type of the class
template <typename TT> // this is the type of the method
void MyClass<T>::MyMethod(const TT & param)
{
// etc.
}
我知道我必须“声明”方法中使用的类型名,但不知道具体如何,通过试验和错误找到。
上面的代码在 Visual C++ 2008 上编译,但是:这是在 T 上模板化的类中在 TT 上模板化方法的正确方法吗?
作为奖励:这种代码背后是否存在隐藏的问题/惊喜/限制? (我想专业写起来会很有趣)
【问题讨论】:
-
至于特化:如果不明确特化包含类,就无法特化成员函数:stackoverflow.com/questions/2097811/…
标签: c++ class templates methods