Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++0x auto cannot deduce the type of vector<int> member function pointer

Using GCC 4.7.0 (g++ -std=c++0x test.cpp) to compile the following simple C++ code gives compile error message: error: unable to deduce ‘auto’ from ‘& std::vector<_Tp, _Alloc>::push_back >’

I question is why in this simple case auto cannot deduce the type of member function pointer?

#include <iostream>
#include <vector>

int main(void) {

    // works 
    void (vector<int>::*pb)(const vector<int>::value_type&)
        = &vector<int>::push_back;

    // not work
    auto pbb = std::mem_fn(&vector<int>::push_back);

    return 0;
}
like image 733
PeopleMoutainPeopleSea Avatar asked Dec 15 '22 08:12

PeopleMoutainPeopleSea


1 Answers

C++11 added an overload for vector::push_back that takes an rvalue argument. mem_fn is unable to deduce which one of the two overloads you wish to take the address of, so you'll need to add a cast to disambiguate.

auto pbb = std::mem_fn(static_cast<void (vector<int>::*)(const vector<int>::value_type&)>(&vector<int>::push_back));

Note that taking the address of a member function of a class in the standard library should be avoided as far as possible. Implementations are allowed to add additional overloads, parameters with default arguments etc., which will make the code non-portable.

§17.6.5.5/2 [member.functions]

For a non-virtual member function described in the C++ standard library, an implementation may declare a different set of member function signatures, provided that any call to the member function that would select an overload from the set of declarations described in this standard behaves as if that overload were selected. [ Note: For instance, an implementation may add parameters with default values, or replace a member function with default arguments with two or more member functions with equivalent behavior, or add additional signatures for a member function name. —end note ]

like image 129
Praetorian Avatar answered Dec 29 '22 01:12

Praetorian