Parameter passing error - c++

I have made a function like this:
void function(Objectx &x);
And I call the function like this:
Objectx o;
function(o);
in the same class.
When I compile it I get this:
error: no matching function for call to ‘function(Objectx)’
note: candidate is: void function (Objectx&)
Sorry if is a lame question, but I didn't find a solution anywhere. Do you have any suggestions?

I don't think you've shown the real code causing the error. (For one thing, the alleged code has Obectx and the error says Objectx)
That error would occur if you passed a temporary value (rvalue), because an non-const reference cannot bind to an rvalue.
If the function doesn't change its parameter, change the signature to:
void function(const Objectx &x);
If the function does change its parameter, you will need to store the temporary value to a variable, and pass the variable. That way any changes made by the function end up in a variable you can access after the call.

Related

Unable to pass function pointer as function param

I would like to pass function pointer as a function parameter.
Here is my code:
void AuthServerOpcodes::ValidateAndSetServerOpcode(ServerOpcode serverOpcode, void(*handlerFunc(std::vector<std::byte> data))) {}
Here is the function I would like to pass as second parameter in ValidateAndSetServerOpcode:
void AuthServerOpcodes::Test(std::vector<std::byte> data) {
std::cout << "all good" << std:end
}
Here is how I try to pass it:
ValidateAndSetServerOpcode(SMSG_LOGIN_REQUEST, &Test);
However this seems to be not the correct way. When I try to do it in that way I get error:
Cannot initialize a parameter of type 'void (*(*)
(std::vector<std::byte>))' with an rvalue of type 'void
(AuthServerOpcodes::*)(std::vector<std::byte>)': different return type
('void (*)' vs 'void')
Why is that and how can I fix it?
Pointers to member must be qualified with the class type, so you need to get the pointer you'll need to use
ValidateAndSetServerOpcode(SMSG_LOGIN_REQUEST, &AuthServerOpcodes::Test);
But it looks like you've tried that in the previous edit, so I guess you've called the function pointer to member incorrectly. You didn't show a minimal, reproducible example so I can't help you more, please create one. Anyway I've created a compiled example on Compiler Explorer
typedef void (AuthServerOpcodes::*HandlerFunc)(std::vector<std::byte> &);
void AuthServerOpcodes::ValidateAndSetServerOpcode(ServerOpcode serverOpcode,
HandlerFunc handlerFunc)
{
std::vector<std::byte> myVector;
(this->*handlerFunc)(myVector); // call the hander
}
void FreeStandingFunction(AuthServerOpcodes& opc,
AuthServerOpcodes::HandlerFunc handlerFunc,
std::vector<std::byte> &data)
{
(opc.*handlerFunc)(data);
}
As you can see the pointer to member must be called with ->* or .* and the whole dereferencing must be wrapped inside () because those operators has lower precedence than the function call operator ()
See also Function pointer to member function
Some off-topic note:
Don't use lines that are too long like that
Don't pass vectors by values unless you really need to preserve the outside value. Always pass by reference with const std::vector<>& (or remove const to modify the outside variable)
Use '\n' instead of std::endl
You can't do that.
There is no function pointer to that function, because it is a member function.
You can instead pass a pointer-to-member-function, or better yet a std::function bound to a lambda that captures the this pointer.
It's just a type mismatch, your function is a method of the AccountManager class,
so it has this signature similar to:
static void Login(AccountManager *this, std::vector<..> data);
You can either detach function from class, change your type definition of handlerFunc or consider different techniques like std::mem_fn or std:bind
https://en.cppreference.com/w/cpp/utility/functional/mem_fn
https://en.cppreference.com/w/cpp/utility/functional/bind

How to take address of non-static member function to use within QtConcurrent?

I'm trying to run non-static member function in the other thread. If I go:
void *(PortManager::*innerAskPtr)() = &this->innerAsk;
QFuture<void> f = QtConcurrent::run(innerAskPtr);
it prompts that
ISO C++ forbids taking the adress of an unqualified or parenthesized non-static member function to form a pointer to member function.
but if I delete this extra reference symbol:
void *(PortManager::*innerAskPtr)() = this->innerAsk;
QFuture<void> f = QtConcurrent::run(innerAskPtr);
it goes that it
cannot convert 'PortManager::innerAsk' from type 'void (PortManager::)()' to type 'void* (PortManager::*)()`
What to add on the right side to get these extra stars (*) on the left?
But still, even if I would get there, there is always another error; about the run(T(*)()):
no matching function for call to 'run(void* (PortManager::*&)())
it's so over my head to understand how this reference got there...
The documentation for QtConcurrent::run seems to explain all this.
Using Member Functions
QtConcurrent::run() also accepts pointers to member functions. The first argument must be either a const reference or a pointer to an instance of the class. Passing by const reference is useful when calling const member functions; passing by pointer is useful for calling non-const member functions that modify the instance.
There are code examples immediately following this text.
In your code:
void *(PortManager::*innerAskPtr)() = this->innerAsk;
QFuture<void> f = QtConcurrent::run(innerAskPtr);
the error message indicates that this->innerAsk returns void, but you are trying to assign it to a pointer-to-member-function returning void *. You probably meant:
void (PortManager::*innerAskPtr)() = &PortManager::innerAsk;
but you don't need to do this in order to call QtConcurrent::run, as the code examples show you can just write:
QtConcurrent::run( this, &PortManager::innerAsk );

The meaning of & as function parameter in a compile error

I'm new to C++ and am trying to interpret what the compiler is telling me. I'm calling the function this way:
Object *clientConnection = new Object();
function(clientConnection);
and getting the following error:
error: no matching function for call to 'function(Object*&)'
I'm trying to give a meaning to the following part Object*&. If I passed a pointer of the Object to the function what's with catch with the &?
It means you passed an lvalue of type Object*. If you passed an rvalue of type Object*, you would see a different error:
function(&*clientConnection);
should give
error: no matching function for call to 'function(Object*)'
This information is part of the error message, because some functions can only be called with lvalues, and if you pass an rvalue, this lack of & points you towards the problem.
You could implement function(clientConnection) in two ways
Call by value where the content of variable clientConnection will
be copied in 'p'
void function(Object* p)
Call by reference where 'p' is an alias of clientConnection in
function body.
void function(Object* &p)
When both of above definitions are missing, the compiler prints one of them mostly
function(Object*&)

No matching function for call (expects reference to pointer instead of pointer)

I get the error from xcode (3.2.4)/gcc(4.0):
/Users/admin/scm/audacity/mac/../src/toolbars/DeviceToolBar.cpp: In member function 'void DeviceToolBar::ShowInputDialog()':
/Users/admin/scm/audacity/mac/../src/toolbars/DeviceToolBar.cpp:817: error: no matching function for call to 'DeviceToolBar::ShowComboDialog(wxChoice*&, wxString)'
/Users/admin/scm/audacity/mac/../src/toolbars/DeviceToolBar.h:74: note: candidates are: void DeviceToolBar::ShowComboDialog(wxChoice*, wxString&)
So it looks like it expects a reference to a pointer in ShowComboDialog, but I don't know why as the signatures are clearly normal pointers. Furthermore if it was expecting a reference to a pointer the way I am calling it should work.
This is the first error, and there are no special warnings before it.
Also, this compiles in MSVC 2008 express.
Please give me a clue.
//in the class def
//(only relevant portions included
class DeviceToolBar:public ToolBar {
public:
DeviceToolBar();
virtual ~DeviceToolBar();
void ShowInputDialog();
private:
void ShowComboDialog(wxChoice *combo, wxString &title);
wxChoice *mInput;
};
//in the cpp file
void DeviceToolBar::ShowInputDialog()
{
ShowComboDialog(mInput, wxString(_("Select Input Device")));
}
void DeviceToolBar::ShowComboDialog(wxChoice *combo, wxString &title)
{
//...
}
The problem is not the first parameter; its the second. You're passing in a temporary wxString, but the function is expecting a reference. C++ will automatically convert a temporary to a const reference, but it cannot convert it to a reference. You need to make ShowComboDialog take a const reference as its second parameter.
Your ShowComboDialog takes a wxString by non-const reference and you are trying to pass a temporary object as an argument to this parameter. You can only bind const references to temporary objects.
You either need to change ShowComboDialog to take its second argument either by value (wxString) or by const reference (const wxString&) or you need to create a variable for the wxString that you create when you call the function and then pass (a reference to) that variable instead.

int transforms into int&?

code snippet:
// some code
SDL_Surface* t = Display->render_text(text);
int z=100;
Display->blit_image(t,z,100);
// some more code
does not compile because z magically changes to an int&,
file.cpp:48: error: no matching function for call to ‘display::blit_image(SDL_Surface*&, int&, int)
how can this happen?
post scriptum:
the following works if i put them in place of Display->blit_image(t,z,100)
Display->blit_image(t,z,100,0);
but i am sure that th 4th param is optional because the exact same function works elsewhere without it
pps: i created a minimal-case of my code that behaves as describd above
it's 3 files:
monkeycard.cpp: http://pastebin.com/pqVg2yDi
display.hpp: http://pastebin.com/xPKgWWbW
display.cpp: http://pastebin.com/nEfFX1wj
g++ -c display.cpp monkeycard.cpp fails with:
monkeycard.cpp: In member function ‘void monkeycard::messagebox(std::string)’:
monkeycard.cpp:28: error: no matching function for call to ‘display::blit_image(SDL_Surface*&, int&, int)’
display.hpp:26: note: candidates are: void display::blit_image(SDL_Surface*, int, int, SDL_Rect*)
The error message tells you what you're trying to pass. With automatic conversions and whatnot, that doesn't mean the function must have exactly that signature.
int& here just means that the parameter you've provided is an lvalue, and so it could be passed as a non-const reference. A function can match with that parameter as an int&, const int&, int, long, const float&, etc.
the point is that if instead of z i
write 100 it works.
That's interesting. I can't immediately think of a way to write a function that accepts an integer literal, but not an integer variable. The following code compiles, of course:
struct SDL_Surface;
struct SDL_Rect;
struct display {
void foo(SDL_Surface* img, int x=0, int y=0, SDL_Rect* clip=0) {}
};
int main() {
display d;
int z = 0;
SDL_Surface *p = 0;
d.foo(p,z,100);
}
So there must be something else you haven't mentioned yet, which causes the issue.
Edit: visitor and Charles Bailey (in a comment) have the answer. The defaults are missing from your declaration of the function, so as far as the compiler is concerned you are trying to call a 4-parameter function with 3 arguments. The & is not the problem.
For future reference: when James McNellis asked you for "the" declaration of your function, he meant the declaration which is visible in the translation unit making the call. In your pastebin code, the definition is not visible in that translation unit, and the compiler cannot reach in to a completely different .cpp file and realise that the function is supposed to have parameter defaults. In C++, default values are set up in the calling code, for reasons to do with how calling conventions work.
Having seen the code, the defaults should be given in the header and not in the implementation file.
When you are compiling "monkeycard.cpp", the compiler has only the information in the headers to work with. The compiler has no idea that blit_image has default arguments, and therefore cannot match the function to call.
I suspect that the function isn't declared properly.
There needs to be a prototype inside the class display scope such as:
void blit_image(SDL_Surface* img, int x=0, int y=0, SDL_Rect* clip=NULL);
When you pass an int & parameter (such as any named variable of type int) to an int argument, the value of the int & is copied into the new object of type int. The difference in types implies a conversion which entails a copy which implements pass-by-value. That is just how the C++ formalism works.
The error message you see is nothing else than a specific convention, which that particular compiler uses to generate error messages in cases like that. Apparently, when the compiler is unable to resolve a function call, it generates an error message where every Lvalue argument is reported as having reference type and every Rvalue argument is reported as having non-reference type. This makes some sense, since references in C++ exist specifically for implementing the concept of run-time-bound Lvalue. In fact, it might even turn out that this is exactly how the overload resolution is implemented internally in that compiler.
As for the reason for the error: the function you are trying to call does not exist (or exists, but has a non-matching set of parameters).
P.S. You said in the comments that the matching function actually does exist. That would mean that there's either a problem with the visibility of the function declaration, or a problem with the code you posted being "fake" (i.e. it is not the code you were actually compiling).
Primitives are not reference types in C++.
How do you know that it's the int& that's the cause for the error? The error simply says that the signature is in error. I'd recommend going back and checking the method signature to see what the root cause is.