引用前向声明 class 作为列表的模板
Reference to forward declared class as template for list
我不能使用对 incomplate(前向声明)class 的引用作为列表的模板。
但是指针工作正常。对于我读过的不完整类型,向量、列表和转发列表是允许的(地图、集合和其他不允许)
这是例子
#include <list>
#include <vector>
class MyClass;
void foo(const MyClass&); //works fine
std::vector<const MyClass&> ref_vec; //error
std::list<const MyClass&> ref_list; //error
std::vector<const MyClass*> p_vec; //works fine
std::list<const MyClass*> p_list; //works fine
class MyClass
{};
void main(){}
这里的问题与前向声明无关。您可以通过将程序更改为以下内容来查看:
#include <list>
#include <vector>
class MyClass
{};
void foo(const MyClass&); //works fine
std::vector<const MyClass&> ref_vec; //error
std::list<const MyClass&> ref_list; //error
std::vector<const MyClass*> p_vec; //works fine
std::list<const MyClass*> p_list; //works fine
int main(){}
标记为 //error
和 /works fine
的行将以完全相同的方式失败。问题是 std::vector
and std::list
are not allowed to have a type which is a reference. The reason for this in C++11 and beyond is that elements must be Erasable, which references are not (more details are in the question Why can't I make a vector of references?).
我不能使用对 incomplate(前向声明)class 的引用作为列表的模板。 但是指针工作正常。对于我读过的不完整类型,向量、列表和转发列表是允许的(地图、集合和其他不允许)
这是例子
#include <list>
#include <vector>
class MyClass;
void foo(const MyClass&); //works fine
std::vector<const MyClass&> ref_vec; //error
std::list<const MyClass&> ref_list; //error
std::vector<const MyClass*> p_vec; //works fine
std::list<const MyClass*> p_list; //works fine
class MyClass
{};
void main(){}
这里的问题与前向声明无关。您可以通过将程序更改为以下内容来查看:
#include <list>
#include <vector>
class MyClass
{};
void foo(const MyClass&); //works fine
std::vector<const MyClass&> ref_vec; //error
std::list<const MyClass&> ref_list; //error
std::vector<const MyClass*> p_vec; //works fine
std::list<const MyClass*> p_list; //works fine
int main(){}
标记为 //error
和 /works fine
的行将以完全相同的方式失败。问题是 std::vector
and std::list
are not allowed to have a type which is a reference. The reason for this in C++11 and beyond is that elements must be Erasable, which references are not (more details are in the question Why can't I make a vector of references?).