Somebody can help me to build this source code in a right way,
I understand that I shold declare the callBack as std::function<void(std::unique_ptr<int>&& param)>
because this take a no copy
constructible param(std::unique_ptr
), so what is the correct type if I no use auto to deduce the type?
#include <functional>
#include <memory>
template <class T>
class SomeClass {
void someFunctionCallback(float o) = 0;
};
template <>
class SomeClass<float> {
public:
SomeClass() = default;
inline void someFunction() {
// std::function<void()>
auto callBack {
std::move(std::bind(&SomeClass<float>::someFunctionCallback,
this,
std::unique_ptr<int>{new int(9)}))};
useCallBack(std::move(callBack));
}
inline void someFunctionCallback(std::unique_ptr<int>&& param) {
}
inline void useCallBack(std::function<void()> &&callBack) {
// callBack();
}
};
int main() {
SomeClass<float> k;
k.someFunction();
return 0;
}
Your code has a couple of problems. First, auto { ... }
will deduce an std::initializer_list
. That's not what you want. Use a brace-or-equal initializer instead.
auto callBack =
std::bind(&SomeClass<float>::someFunctionCallback,
this,
std::unique_ptr<int>{new int(9)});
Second, your function takes an rvalue-reference, but std::bind
will pass an lvalue. Read Passing rvalues through std::bind for a full explanation, but as a workaround you can use this ugly cast:
using uptr = std::unique_ptr<int>;
auto callBack =
std::bind(&SomeClass<float>::someFunctionCallback,
this,
std::bind(static_cast<uptr&&(&)(uptr&)>(std::move<uptr&>),
std::unique_ptr<int>{new int(9)})
) ;
Finally, just make your function a template. The whole idea is not to worry about the type, and auto
follows the rules of template argument deduction anyway.
template <typename T>
inline void useCallBack(T callBack) {
callBack();
}