简体   繁体   English

不完整类型的C ++导出模板实现

[英]C++ export template implementation of incomplete type

I have the following scenario: 我有以下情况:

header.h: header.h:

class A
{
    public:

    class B; // incomplete type

private:
    // is never used outside of source file for A
    std::vector<B> vector_of_bs; // template
}

source1.cpp: source1.cpp:

class A::B {}; // defined here

All is good until here. 一切都很好,直到这里。 Now if I want to use class A elsewhere it doesn't work: 现在,如果我想在其他地方使用class A ,则无法使用:

source2.cpp : uses class A and doesn't compile with source2.cpp :使用类A且不与

vector(721): error C2036: 'A::B *' : unknown size 向量(721):错误C2036:'A :: B *':未知大小

while compiling class template member function 'std::vector<_Ty> &std::vector<_Ty>::operator =(const std::vector<_Ty> &)' 同时编译类模板成员函数'std :: vector <_Ty>&std :: vector <_Ty> :: operator =(const std :: vector <_Ty>&)'

in VS2010. 在VS2010中。 How can I link against the template specialisation of std::vector in source1.o? 如何链接到source1.o中std :: vector的模板专业化?

I also need to use this with declspec(_dllimport) ... 我还需要将其与declspec(_dllimport)一起使用...

Standard library containers cannot be instantiated with incomplete types . 标准库容器不能使用不完整的类型实例化 To do so is undefined behaviour, and in your case produces a clear error. 这样做是不确定的行为,在您的情况下会产生明显的错误。 Other implementations would silently accept your code. 其他实现将静默地接受您的代码。

To address this issue, boost provides counterparts for the standard library containers that can in fact be instantiated with incomplete types . 为了解决这个问题,boost提供了标准库容器的副本,实际上可以使用不完整的类型实例化这些库 You could replace std::vector with the boost counterpart to fix your code: 您可以用boost替换std::vector来修复代码:

#include <boost/container/vector.hpp>

class A
{
 public: 
    class B; // incomplete type

 private:
    boost::vector<B> vector_of_bs;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM