如何在名称空间std中转发声明模板类? [英] How to forward declare a template class in namespace std?
问题描述
#ifndef __TEST__
#define __TEST__
命名空间std
{
模板< typename T>
班级名单;
}
模板< typename T>
void Pop(std :: list< T> * l)
{
while(!l-> empty())
l-> pop();
}
#endif
主要。我收到错误。当然,我知道 std :: list
(我认为是分配器)有更多的模板参数。但是,这是重要的。我必须知道模板类的完整模板声明才能够转发声明吗?
问题不在于您无法转发声明模板类。是的,您需要知道所有模板参数及其默认值才能正确地转发声明:
namespace std {
template< class T,class Allocator = std :: allocator< T>>
班级名单;
}
但是为了在命名空间中创建这样的前向声明std
被标准明确禁止:允许放入 的东西 std
是一个模板 specialization ,通常 std :: less
在用户定义的类型上。
只要 #include< list>
并且不用担心,如果有必要的话,其他人可以引用相关文本。
TEST_H / code>而不是 __ TEST __
。它不会生成警告或错误,但是如果程序与实现定义的标识符发生冲突,则不能保证能够正确编译或运行:它是不正确的 。还禁止使用以下划线开头的名称,后面跟着大写字母等等。一般来说,除非你知道你在处理什么魔法,否则不要用下划线开始。
#ifndef __TEST__
#define __TEST__
namespace std
{
template<typename T>
class list;
}
template<typename T>
void Pop(std::list<T> * l)
{
while(!l->empty())
l->pop();
}
#endif
and used that function in my main. I get errors. Of course, I know that there are more template params for std::list
(allocator I think). But, that is beside the point. Do I have to know the full template declaration of a template class to be able to forward declare it?
EDIT: I wasn't using a pointer before - it was a reference. I'll try it out with the pointer.
解决方案 The problem is not that you can't forward-declare a template class. Yes, you do need to know all of the template parameters and their defaults to be able to forward-declare it correctly:
namespace std {
template<class T, class Allocator = std::allocator<T>>
class list;
}
But to make even such a forward declaration in namespace std
is explicitly prohibited by the standard: the only thing you're allowed to put in std
is a template specialisation, commonly std::less
on a user-defined type. Someone else can cite the relevant text if necessary.
Just #include <list>
and don't worry about it.
Oh, incidentally, any name containing double-underscores is reserved for use by the implementation, so you should use something like TEST_H
instead of __TEST__
. It's not going to generate a warning or an error, but if your program has a clash with an implementation-defined identifier, then it's not guaranteed to compile or run correctly: it's ill-formed. Also prohibited are names beginning with an underscore followed by a capital letter, among others. In general, don't start things with underscores unless you know what magic you're dealing with.
这篇关于如何在名称空间std中转发声明模板类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!