I'm writing a delegate for class method. Sample code below:
template <typename T> class Delegate;
template<typename R, typename ...Args>
class Delegate<R(Args...)> final {
public:
Delegate(const Delegate& rhs) : obj_(rhs.obj_), stub_(rhs.stub_) {}
template <class T, R(T::*TMethod)(Args...)>
static Delegate create(T* instance) {
return Delegate(instance, method_stub<T, TMethod>);
} //create
template <typename ...B>
R operator()(B &&... args) const {
return (*stub_)(obj_, std::forward<B>(args)...);
} //operator()
private:
using stub_t = R(*)(void*, Args&&...);
void* obj_ = nullptr;
stub_t stub_ = nullptr;
Delegate(void* obj, stub_t stub) : obj_(obj), stub_(stub) {
} //delegate
template <class T, R(T::*TMethod)(Args...)>
static R method_stub(void* obj, Args &&... args) {
T* p = static_cast<T*>(obj);
return (p->*TMethod)(std::forward<Args>(args)...);
} //method_stub
};
class Sample {
long m;
public:
double A(int) {
std::cout << "Sample::A" << std::endl;
return 0.1;
}
}; //class Sample
int main() {
Sample sample;
Delegate<double(int)> myfunc = Delegate<double(int)>::create<Sample, &Sample::A>(&sample);
int k = 9;
myfunc(k);
}
However, the above code won't compile, complaining the line in R operator()(B &&... args) const when compiling the the last line in the main function.
error: cannot bind rvalue reference of type ‘int&&’ to lvalue of type ‘int’
Since I declare function call operator as template member function, and use std::forward to forward the params, why I'm stilling seeing the error above?