lundi 4 juin 2018

How can I use std::result_of to return the function type instead of void

I am trying to get the return type of a function that I bind in. So in this instance I was expecting to see the return type of GetFactorialResult (so int).

#include <iostream>
#include <boost/core/demangle.hpp>
#include <typeinfo>

namespace
{
    const int testNumber = 10;
    int GetFactorialResult(int number)
    {
        if (number > 1)
        {
            return number * GetFactorialResult(number - 1);
        }
        else
        {
            return 1;
        }
    }

    template <typename Func, typename... Args>
    void Submit(Func&& func, Args&&... args)
    {
        auto boundTask = std::bind(std::forward<Func>(func), std::forward<Args>(args)...);
        using ResultType = typename std::result_of<decltype(boundTask)()>::type;

        char const * name = typeid( ResultType ).name();
        std::cout << boost::core::demangle( name ) << std::endl;
    }
}


int main()
{
    Submit([](int number)
        {
        GetFactorialResult(number);
        }, number);

    return 0;
}

The output I see is the following:

void
0

When I print the type of boundTask, I see what I expect:

std::_Bind<\main::{lambda(int)#1} (int)> (the backslash doesnt exist, but couldnt figure out how to display it without it).

I assume I am getting void because of I'm doing decltype(boundTask)(), but if I remove the parenthesis, it fails to compile. I thought I had a good grasp on using result_of, but clearly I need to understand more - Any help would be greatly appreciated! I only have access to c++11 features.

Aucun commentaire:

Enregistrer un commentaire