模板方法中的C++11自动返回类型

C++11 auto return type in template methods

本文关键字:返回类型 C++11 模板方法      更新时间:2023-10-16

我想写一个通用函数来在不同的容器中搜索。CoinContainer包含指向不同类型的共享指针。目前我有这个

    template<typename TInstance, typename THandle, typename TContainer>
    auto FindInContainer(TContainer& container, THandle handle) -> decltype(boost::shared_ptr<TInstance>())
    {
        std::lock_guard<std::mutex> lock(_mutex);
        const auto& found = std::find_if(container.begin(), container.end(), 
            [handle](typename TContainer::value_type& instance)
            {
                return instance.get() == reinterpret_cast<typename TContainer::value_type::element_type*>(handle.handle);
            });
        if (found == container.end())
            return boost::shared_ptr<TInstance>();
        return *found;
    }

我使用MSVC 2015 Update 1,但不知何故,它无法计算出TInstance类型,即使我使用了指定的返回类型(无论方法签名中->运算符的术语是什么)。

return FindInContainer<SensorController>(_sensors, handle); // Works
return FindInContainer(_sensors, handle); // Does not compile

传感器定义为(_S)

std::vector<boost::shared_ptr<SensorController>> _sensors;

是我的C++生锈了,还是编译器不支持这种类型推导?

不能从函数模板的返回类型推导出模板参数。只有函数模板的参数参与模板参数推导。由于TInstance没有出现在FindInContainer的任何参数中,因此无法推导。

如果VS 2015 Update 1支持它,您可以对函数模板使用返回类型推导(C++14特性)(完全省略返回类型):

template<typename THandle, typename TContainer>
auto FindInContainer(TContainer& container, THandle handle)
{
  // ... as before
}

如果不支持,您可以从容器中提取类型(就像您已经在做的那样):

template<typename THandle, typename TContainer>
typename TContainer::value_type FindInContainer(/*...*/)
{
  // ... as before
}