I have:
class MyClass
{
Something<float> m_something;
void DoThisAndThat()
{
CallMethod(m_something);
}
};
That CallMethod() is of the form:
void CallMethod(Something<float>&&);
For some reason the compiler complains that there's no matching method to call that CallMethod():
"Candidate function not viable: no known conversion from 'Something<float>' to 'Something<float>&&'.
What is wrong? How to fix this? As far as I understand, that should work as it is.
EDIT:
Here is a minimum viable example which demonstrates my situation:
template<typename T>
class Something
{
public:
T data;
};
class MyOtherClass
{
public:
void CallMethod(Something<float>&& something)
{
}
};
class MyClass
{
public:
void DoThisAndThat()
{
m_my_other_class.CallMethod(m_something);
}
MyOtherClass m_my_other_class;
Something<float> m_something;
};
CallMethod expects an argument that can be bound to an rvalue reference (Something<float>&&).
But m_something is an lvalue. it cannot be bound to an rvalue reference.
This is the cause for the compilation error.
You mentioned in a comment that you cannot change the API CallMethod.
We also don't know what it actually does with the parameter.
So, there are 2 ways you can modify the call to CallMethod and supply a proper argument:
If you don't need m_something after the call, you can use move (from <utility> header) to cast to an rvalue and indicate that the callee can take ownership:
CallMethod(std::move(m_something));
Live demo 1
If you need m_something, and it is copyable, you can create a temporary copy of it and pass the copy which is an rvalue:
CallMethod(Something{ m_something });
Live demo 2
Note:
As @cigien commented, from C++23 you can also use auto for the type and leave it to the compiler to deduce:
CallMethod(auto{ m_something });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With