从函数参数的返回类型推断函数返回类型

Deducing the function return type from its parameter's return type

本文关键字:返回类型 函数 参数      更新时间:2023-10-16

下面有代码

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的类型?

2010年作品:

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

您需要使用decltype和尾随返回类型。它们都是c++ 11的特性,但是根据MSDN的说法,Visual Studio 2010应该会支持它们。你还需要一个类型trait来从vector中提取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