将容器的原始指针和智能指针传递给模板功能

时间:2015-09-21 08:33:59

标签: c++ templates c++11 unique-ptr

当容器(例如: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有用吗?我找不到办法做到这一点。

需要这个的基本原理是旧代码使用原始指针和带有智能指针的新代码调用方法,因此无法快速切换到新模式。

1 个答案:

答案 0 :(得分:5)

使用std::pointer_traits<T>

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]);
    }
}

DEMO