【问题标题】:How to use an STL container to hold template based shared_ptr?如何使用 STL 容器来保存基于模板的 shared_ptr?
【发布时间】:2014-02-06 02:23:41
【问题描述】:

我想构建一个容器来保存基于模板的 shared_ptrs。例如,我有:

template <class T>
class Data
{
    ....
};

template <class T>
struct DataPtr {
    typedef boost::shared_ptr<Data<T> > type;
};

template <class T>
struct mapData {
    typedef typename std::map<std::string, DataPtr<T>::type > type;
};

mapData<int>::type data;
void func(const std::string& str, DataPtr<int>::type& sth)
{
    if (sth)
    {
        data[str] = sth;
    }
}

现在我有一些问题。编译器不允许我在定义 mapData 时使用 DataPtr::type,错误消息是“期望一个类型,得到‘dataPtr::type”。如果我放弃类型并使用

template <class T>
struct mapData {
    typedef typename std::map<std::string, DataPtr<T> > type;
};

那么“data[str] = sth”不通过(“no match for ‘operator=’”)。

正确的方法应该是什么?

非常感谢。

【问题讨论】:

    标签: c++ templates stl containers shared-ptr


    【解决方案1】:

    你放错了typename关键字的位置:

    typedef std::map<std::string, typename DataPtr<T>::type > type;
    //                            ^^^^^^^^
    

    【讨论】:

      猜你喜欢
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 2019-05-24
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      相关资源
      最近更新 更多