c++ - 如何使用 STL 容器来保存基于模板的 shared_ptr?

标签 c++ templates stl containers shared-ptr

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

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,错误消息是“expected a type, got ‘dataPtr::type”。如果我放弃类型并使用

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

然后“data[str] = sth”没有通过(“不匹配‘operator=’”)。

正确的做法应该是怎样的?

非常感谢。

最佳答案

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

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

关于c++ - 如何使用 STL 容器来保存基于模板的 shared_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21592822/

相关文章:

c++ - 使用 Eclipse 的代码完成来 boost

c++ - 是否可以使用 std::enable_if 来选择成员模板特化?

c++ - 调用 glDrawArrays 后出现 SegFault

c++ - 我什么时候通过 const& std::string 而不是 std::string_view ?

c++ - std::getline() 如何等同于 bool?

c++ - 用于替换 map vector 的外部存储器数据结构

c++ - 此 C++ 堆栈分配器的改进?

c++ - 使用 boost::iterator_facade<> 为迭代器返回 ref 但为 const_iterator 返回 const_ref?

c++ - 使用模板模板类参数作为参数

c++ - 为什么 C++ 在有 !范围内的运营商?