[英]C++ Error when mixing template class and template method
I have a class that takes a size type as a parameter in case one doesn't want to use size_t or another hard coded type which would require casting and checking for overflows. 我有一个类,它将一个size类型作为参数,以防一个人不想使用size_t或另一个需要转换和检查溢出的硬编码类型。 This class also has some methods taking a second template type : 这个类还有一些方法采用第二种模板类型:
template< typename SizeType = uint32_t >
class BufferReader
{
SizeType m_nPosition;
template< typename T >
T Read();
}
My problem is, what is the syntax to implement this ? 我的问题是,实现这个的语法是什么?
template< typename SizeType, typename T >
T BufferReader< SizeType >::Read()
{
// ...
}
Which gives me an error : 这给了我一个错误:
invalid use of incomplete type 'class core::BufferReader<SizeType>'
Or : 要么 :
template< typename T >
template< typename SizeType >
T BufferReader< SizeType >::Read()
{
// ...
}
Which gives the same error. 这给出了同样的错误。
Or anything else ? 还是其他什么?
Thank you ! 谢谢 !
Your second example is nearly right, you just need to have the template parameters of the class first and those of the function second: 你的第二个例子几乎是正确的,你只需要先让类的模板参数和第二个函数的模板参数:
template< typename SizeType >
template< typename T >
T BufferReader< SizeType >::Read()
{
// ...
}
You almost got it. 你几乎得到了它。 You have to stack the template
s as in the declaration: first the class and then the member. 您必须像声明中那样堆叠template
:首先是类,然后是成员。
template < typename SizeT >
template < typename T >
T
BufferReader<SizeT>::Read()
{
return T {};
}
Note that the code can be simplified by defining the function right in the class body but I understand that some people will prefer to separate declaration from definition for aesthetic reasons. 请注意,可以通过在类体中定义函数来简化代码,但我理解为了美学原因,有些人更愿意将声明与定义分开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.