模板方法中的C++11自动返回类型
C++11 auto return type in template methods
我想写一个通用函数来在不同的容器中搜索。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
}
相关文章:
- c++ 11 带有 decltype 的尾随返回类型无法按预期工作
- 在 C++11 函数中使用尾随返回类型的优点
- 具有尾随返回类型的通用 lambda,具体取决于 C++11 中的可变参数
- BackPort C 14返回类型扣除对C 11
- C++11 中的 decltype(auto) - 推断返回类型
- 是在C 11中没有返回类型的主机的使用情况
- 找出函子的返回类型 C++11Boost
- 这种尾随返回类型在C++11中合法吗
- 如何获取 lambda 的返回类型,在 C++11 中归约函数
- C++11:return_type(对于 std::bind),其中返回类型基于输入类型
- 我们什么时候可以省略 C++11 lambda 中的返回类型
- C++11 非模板化基类中的纯虚拟'templated'返回类型
- 如何在 C++11 之前模拟尾随返回类型的 decltype
- C++11 在特定情况下避免冗余返回类型
- 返回类型的C++11 方法模板专用化
- C++11对lambda返回类型的限制
- 带有返回类型推导的C++11运算符重载
- 在C++11中确定泛型返回类型时出错
- 模板方法中的C++11自动返回类型
- 如何确定C++11成员函数的返回类型