Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 227
Kadir Erdem Demir Avatar asked Dec 06 '25 19:12

Kadir Erdem Demir


2 Answers

Works in 2010:

template<typename F>
auto GetListAndSearchName (F listGetter, const std::string& stringName) 
  -> decltype(listGetter(myList[0])[0])
like image 88
n. 1.8e9-where's-my-share m. Avatar answered Dec 08 '25 10:12

n. 1.8e9-where's-my-share m.


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
like image 23
zedu Avatar answered Dec 08 '25 10:12

zedu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!