【问题标题】:Deducing the function return type from its parameter's return type从参数的返回类型推导出函数返回类型
【发布时间】:2016-11-18 15:30:45
【问题描述】:

我有下面的代码

template<typename U, typename F >
U GetListAndSearchName( F listGetter, const std::string& stringName )
{
    std::vector<UserType> newList;
    for ( size_t i = 0; i < myList.size(); i++)
    {
        const std::vector<U>& list = listGetter(myList[i]);
        for ( size_t i = 0; i < list.size(); i++ )
        {
            if ( list[i]->GetName() == stringName )
                return list[i];
        }
    }
    return U();
}

即使 U 存在于我的函数指针的返回类型中,它是模板参数 F(我稍后使用 std::mem_fn 创建它 F 也可能是 std::function)目前我需要将 U 的类型显式传递给编译器.

如何让我的旧 Vs2010 编译器推断 U 的类型?

【问题讨论】:

  • 你不能。返回类型本身不能推导出来。
  • 我已经加入了一个特定的标准标签。我不确定这在 C++03 中是否容易解决。
  • 你不能在 c++03 中,你可以在 C++14 中使用decltype(auto)
  • 寻找function_traits。
  • @101010 如果你有时间,也许你可以把它写成答案。即使对我没有用,它也可能是别人的答案。

标签: c++ visual-studio-2010 templates c++03


【解决方案1】:

2010 年工作:

template<typename F>
auto GetListAndSearchName (F listGetter, const std::string& stringName) 
  -> decltype(listGetter(myList[0])[0])

【讨论】:

  • 不错。解决了:: 问题。
  • 如果列表为空会发生什么
  • @KadirErdemDemir decltype 内部的表达式没有被计算,所以没有什么不好的事情发生。
【解决方案2】:

您需要使用 decltype 和尾随返回类型。它们都是 C++11 功能,但根据 MSDN,Visual Studio 2010 应该支持它们。您还需要一个类型特征来从向量中提取 value_type。

template<typename T>
struct value_type { typedef T::value_type type; };

template<typename F>
auto GetListAndSearchName( F listGetter, const std::string& stringName )
    -> typename value_type<decltype(listGetter(myList[0]))>::type

【讨论】:

  • 原则上是正确的,但要绕过 VS2010 对 decltype 的限制,您可能需要一个单独的 trait 来提取 element_type。我相信它不喜欢使用 ::decltype 作为 LHS 运算符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-04
  • 1970-01-01
相关资源
最近更新 更多