【问题标题】:C++ export template implementation of incomplete type不完整类型的C++导出模板实现
【发布时间】:2015-02-09 11:50:47
【问题描述】:

我有以下场景:

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:

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

到这里为止一切都很好。现在,如果我想在其他地方使用class A,它就行不通了:

source2.cpp: 使用 A 类且不编译

vector(721): error C2036: 'A::B *' : 未知大小

在编译类模板成员函数'std::vector<_ty> &std::vector<_ty>::operator =(const std::vector<_ty> &)'时

在 VS2010 中。如何链接 source1.o 中 std::vector 的模板特化?

我还需要将它与declspec(_dllimport)...一起使用...

【问题讨论】:

    标签: c++ templates forward-declaration


    【解决方案1】:

    标准库容器cannot be instantiated with incomplete types。这样做是未定义的行为,并且在您的情况下会产生明显的错误。其他实现会默默地接受您的代码。

    为了解决这个问题,boost 提供了counterparts for the standard library containers that can in fact be instantiated with incomplete types。您可以将 std::vector 替换为 boost 对应项来修复您的代码:

    #include <boost/container/vector.hpp>
    
    class A
    {
     public: 
        class B; // incomplete type
    
     private:
        boost::vector<B> vector_of_bs;
    };
    

    【讨论】:

    • 我认为这还不够。 B 必须在生成复制赋值/析构函数/复制构造函数等时完成,因此您可能需要在类定义中显式声明,然后在 B 完成的源文件中显式默认,类似于带有unique_ptr 的粉刺。
    猜你喜欢
    • 2014-11-22
    • 2019-06-21
    • 1970-01-01
    • 2017-11-21
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多