【发布时间】:2012-01-23 15:36:02
【问题描述】:
我试图将 boost::share_ptr 集成到一对模板类中,这些类最初是从我找到的 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::shared_ptr 一切编译正常。
另外,我可以在模板之外的代码中使用类型。
【问题讨论】:
标签: c++ templates boost compiler-errors shared-ptr