T 上的模板化方法位于 TT 上的模板化类内:这可能/正确吗
我有一个类 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 上模板化方法的正确方法吗?
作为奖励:背后是否存在隐藏的问题/惊喜/约束这种代码? (我想专业写起来会很有趣)
I have a class MyClass which is templated on typename T. But inside, I want a method which is templated on another type TT (which is unrelated to T).
After reading/tinkering, I found the following notation:
template <typename T>
class MyClass
{
public :
template<typename TT>
void MyMethod(const TT & param) ;
} ;
For stylistic reasons (I like to have my templated class declaration in one header file, and the method definitions in another header file), I won't define the method inside the class declaration. So, I have to write it as:
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.
}
I knew I had to "declare" the typenames used in the method, but didn't know how exactly, and found through trials and errors.
The code above compiles on Visual C++ 2008, but: Is this the correct way to have a method templated on TT inside a class templated on T?
As a bonus: Are there hidden problems/surprises/constraints behind this kind of code? (I guess the specializations can be quite amusing to write)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这确实是做你想做的事情的正确方法,并且它适用于每个像样的 C++ 编译器。我在 gcc4.4 和最新的 clang 版本上测试了它。
任何类型的代码背后都存在问题/惊喜/限制。
这段代码最终可能遇到的主要问题是,您无法将模板化函数设为虚拟,因此,如果您想在模板化函数的类级别获得多态性,则需要使用外部函数来实现它。
This is indeed the correct way of doing what you want to do, and it will work on every decent C++ compiler. I tested it on gcc4.4 and the latest clang release.
There are problems/surprises/constraints behind any kind of code.
The major issue you could eventually run in with this code is that you can't make a templated function virtual, so if you want to get polymorphism at the class level for your templated function, you're off implementing it with an external function.
我认为这样做是可以的。看一下 std::vector 实现的示例。您有类向量,它有一些模板参数(最明显的是元素类型),并且在内部,其构造函数之一的声明方式与您的方法类似。它有 InputIterator 作为模板参数。所以我认为这并不是什么罕见的做法。
I think It's OK to do that. Take a look for example at std::vector implementation. You have class vector, which has a few template parameters (most notably an element type), and inside, one of its constructors is declared in similar way as your method. It has InputIterator as a template parameter. So I think that this is not so uncommon practice.