简体   繁体   中英

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

I have the code below

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

Even U exists in my function pointer's return type which is template parameter F(I am using std::mem_fn to create it later F might be std::function as well ) currently I am needing to explicitly pass U's type to compiler.

How can I have my old Vs2010 compiler to deduce U's type ?

Works in 2010:

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

You need to use decltype and trailing return types. They are both C++11 features, but according to MSDN they should be supported by Visual Studio 2010. You need also a type trait to extract value_type from vector.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM