I am trying to write a class similar to std::function, just to learn how it works but I am having problem determining the return type of the function.
I found this from one of the answers here on stack overflow. I am trying to do something similar but It does not work and I do not know why.
template< class Fx >
class function
{
public:
function() = default;
function(Fx* fx)
{
this->fx = fx;
}
template < class... A >
ReturnType operator()(A... args)
{
//return ((*fx)(args), ...); ??
}
private:
template<class F>
struct return_type;
template< class R, class... A>
struct return_type<R(*)(A...)>
{
using type = R;
};
using ReturnType = return_type<Fx>::type;
Fx* fx;
};
int sum(int a, int b) { return a + b; };
int main()
{
function<int(int, int)> mysum{ sum };
mysum(10, 10);
}
It gives me an error on line
using ReturnType = return_type<Fx>::type;
saying incomplete type is not allowed. Why does it not pick the specialized one?
>Solution :
Since Fx is supposed to be a function type, not a function pointer type, so the specialization should be declared as:
template< class R, class... A>
struct return_type<R(A...)>
{
using type = R;
};
Other issues:
-
Change
using ReturnType = return_type<Fx>::type;tousing ReturnType = typename return_type<Fx>::type;. -
Move the declaration of
ReturnType(and definition ofreturn_type) before using it as the return type ofoperator(). -
Change
return ((*fx)(args), ...);toreturn (*fx)(args...);in theoperator(); i.e. all the arguments are supposed to be passed tofxinstead of callingfxmultiple times with each argument.
BTW: Return type deduction is worthy of consideration too. E.g.
template < class... A >
auto operator()(A... args)
{
return (*fx)(args...);
}