Pointer to deque <int> :: push_back
#include <iostream> #include <deque> using namespace std; main() { typedef void (deque<int>::*func_ptr)(int); func_ptr fptr = &deque<int>::push_back; }
Im trying to get a pointer to this function, but I get a compilation error
error: cannot convert 'void (std::deque<int>::*)(const value_type&) {aka void (std::deque<int>::*)(const int&)}' to 'func_ptr {aka void (std::deque<int>::*)(int)}' in initialization func_ptr fptr = &deque<int>::push_back;
I want to do this so that I can get a pointer to different member functions based on different conditions.
I named this link .
As the accepted answer says, the problem is that the type signature is different - for std::deque<T>
, push_back
only has an overload that accepts T const&
, and not T
directly. typedef void (deque<int>::*func_ptr)(const int &)
is a very concise and complicated way to write this.
I wanted to turn to C ++ 11 to do this - enter aliases. First you might wonder, “Why not use auto
?” This is not possible because the available function is an overloaded function, and auto
does not know which of the overloads to access. Since the original question introduces knowledge of the type of the void(int)
function, the &deque<int>::push_back
operator selects the correct overload. The problem with the simpler statement is that it bakes knowledge of the container and the type contained in it. If you want to switch to std::vector
or from int
to short
, you will have to create all new types. Using type aliases, we can template everything to avoid entering knowledge types:
using func_ptr = void(Cont::*)(typename Cont::const_reference);
We can do something simple as before:
func_ptr<deque<int>> fptr = &deque<int>::push_back;
... or we can reference the container somewhere:
vector<short> container;
... search for its type at compile time and save a pointer to its push_back
function, regardless of what the container is:
using container_type = decltype(container); func_ptr<container_type> fptr2 = &container_type::push_back;
There is a big problem with what you are trying to do. Implementations are allowed to add default parameters for any member functions, so the actual signature for push_back()
may vary. It may even add additional features with the same name (but a different signature).
I advise against accepting pointers to container functions. You are usually better off without it.