当容器(例如:std::vector
)传递给函数模板时,是否有可能从容器中抽象出对象的指针类型?
我有以下两种方法:
template <typename T, typename allocT, template <typename, typename> class containerT>
static void parse(containerT<T *, allocT> &entries, const rapidjson::Value &jsonDocument)
{
for (rapidjson::SizeType entryIt = 0; entryIt < jsonDocument.Size(); ++entryIt)
{
entries.push_back(new T());
entries[entryIt]->parse(jsonDocument[entryIt]);
}
}
和
template <typename T, typename allocT, template <typename, typename> class containerT>
static void parse(containerT<std::unique_ptr<T>, allocT> &entries, const rapidjson::Value &jsonDocument)
{
for (rapidjson::SizeType entryIt = 0; entryIt < jsonDocument.Size(); ++entryIt)
{
entries.push_back(std::move(std::unique_ptr<T>(new T())));
entries[entryIt]->parse(jsonDocument[entryIt]);
}
}
让我们暂时忽略 std::move
调用。如您所见,这两种方法几乎做同样的事情,除了在推回新对象时。如果我只能有一种方法就更好了。
如何实现? decltype
有用吗?我找不到执行此操作的方法。
需要这样做的基本原理是旧代码使用原始指针调用方法,而新代码使用智能指针调用方法,因此无法快速切换到新模式。
最佳答案
template <typename P, typename allocT, template <typename, typename> class containerT>
static void parse(containerT<P, allocT> &entries, const rapidjson::Value &jsonDocument)
{
for (rapidjson::SizeType entryIt = 0; entryIt < jsonDocument.Size(); ++entryIt)
{
entries.emplace_back(new typename std::pointer_traits<P>::element_type());
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
entries[entryIt]->parse(jsonDocument[entryIt]);
}
}
关于c++ - 将原始指针和智能指针的容器传递给模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32690673/