我想构建一个容器来容纳基于模板的 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/