Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to determine the return type of a function in template

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

  1. Change using ReturnType = return_type<Fx>::type; to using ReturnType = typename return_type<Fx>::type;.

  2. Move the declaration of ReturnType (and definition of return_type) before using it as the return type of operator().

  3. Change return ((*fx)(args), ...); to return (*fx)(args...); in the operator(); i.e. all the arguments are supposed to be passed to fx instead of calling fx multiple times with each argument.

LIVE

BTW: Return type deduction is worthy of consideration too. E.g.

template < class... A >
auto operator()(A... args)
{
    return (*fx)(args...);
}

LIVE

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading