c++ - 为什么定义模板类的 boost::shared_ptr 与非模板类的 boost::shared_ptr 行为不同

标签 c++ templates boost compiler-errors shared-ptr

我试图将 boost::share_ptr 集成到一对模板类中,这对模板类最初派生 self 发现的 boost::asio 示例。当我在一个类中定义一个类型时,它是该类的 shared::ptr 。我似乎无法在另一个模板化类中引用该类型。如果我从代码中删除模板,它就会全部编译。

这不会编译:

#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

using namespace std;

template <typename TSomething1>
class SomeTemplateT : public boost::enable_shared_from_this<SomeTemplateT<TSomething1> >
{
public:
    typedef boost::shared_ptr<SomeTemplateT<TSomething1> > Ptr;

    static Ptr Create()
    {
        return Ptr(new SomeTemplateT<TSomething1>());
    }

    SomeTemplateT()
    {
        cout << "SomeTemplateT created" << endl;
    }
};

template <typename TSomething>
class OtherTemplateT
{
public:
    OtherTemplateT()
    {
        // COMPILATION ERROR HERE
        SomeTemplateT<TSomething>::Ptr someTemplate = SomeTemplateT<TSomething>::Create(); 
    }

private:

};

上面的代码会产生以下编译错误:

src\Templates\main.cpp: In constructor 'OtherTemplateT<TSomething>::OtherTemplateT()':
src\comps\oamp\src\Templates\main.cpp:30: error: expected ';' before 'someTemplate'

在没有模板的情况下使用几乎相同的代码可以毫无困难地编译:

class SomeTemplateT : public boost::enable_shared_from_this<SomeTemplateT>
{
public:
    typedef boost::shared_ptr<SomeTemplateT> Ptr;

    static Ptr Create()
    {
        return Ptr(new SomeTemplateT());
    }

    SomeTemplateT()
    {
        cout << "SomeTemplateT created" << endl;
    }
};

class OtherTemplateT
{
public:
    OtherTemplateT()
    {
        SomeTemplateT::Ptr someTemplate = SomeTemplateT::Create();
    }

private:

};

平台信息: 我在 Windows XP 上使用 MinGW 的 gcc4.4.0(代码:Blocks IDE)。

我做错了什么吗?

编辑: 我忘了提到,如果我用共享 ptr 的完整声明替换 Ptr typedef 的使用: boost::共享指针 一切都编译得很好。

另外,我可以在模板之外的代码中使用类型。

最佳答案

SomeTemplateT<TSomething>::Ptr是一个相关名称;也就是说,它的定义取决于模板参数。除非您这么说,否则编译器不能假定它是类型名称:

typename SomeTemplateT<TSomething>::Ptr someTemplate = SomeTemplateT<TSomething>::Create();
^^^^^^^^

关于c++ - 为什么定义模板类的 boost::shared_ptr 与非模板类的 boost::shared_ptr 行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8974177/

相关文章:

C++ 代码与模板方法调用混淆

C++ 模板特化和子类化

c++ - 是否有用于 boost.build 的 IDE(最好是 netbeans)插件?

c++ - 如何以及为什么要使用 Boost 信号2?

c++ - Boost CRC CCITT 输出值不同

c++ 到 vb.net,回调函数的问题

c++ - shared_ptr 奇怪的行为

调用 draw() 函数时,c++ vector 大小为零

javascript - 为什么可汗学院使用只有空白的模板?

c++ - 在OpenGL中实现边界球碰撞