Wimps
Wimps

Reputation: 489

Std function with unknown return type

I'm trying to declare a std function without directly knowing the return type.

Obviously, it will be known at compile time, but I can't find a right way to declare it.

On top of that, I need to create a container which will contain values from the return of this function.

template <typename... Args>
class Sample
{
public:
    Sample(Args... args, std::function</*unknown return type*/(Args...)> fnct) :
        _inputBuff(std::forward_as_tuple(std::forward<Args>(args)...))

    { }

    std::tuple<Args...>                     _inputBuff;
    std::vector</*unknown return type*/>    _resultBuff;

};

Any ideas ?

Upvotes: 3

Views: 1803

Answers (2)

Guillaume Racicot
Guillaume Racicot

Reputation: 41760

You could accept a callable type in your template arguments instead of a list of parameters. That will allow you to send any function or function object and to inspect the return type:

template<typename F, typename... Args>
struct Sample {
    Sample(F fnct, Args... args) :
        _inputBuff{std::forward_as_tuple(std::forward<Args>(args)...)} { }

    using Result = std::result_of_t<F(Args...)>;

    std::tuple<Args...> _inputBuff;
    std::vector<Result> _resultBuff;
};

In order to ease construction of that class, you can introduce a make function that will deduce parameters (note that it can become a deduction guide in C++17):

template<typename F, typename... Args>
auto makeSample(F&& fnct, Args&&... args) {
    return Sample<std::decay_t<F>, Args...>{std::forward<F>(f), std::forward<Args>(args)...};
}

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

You didn't know the function arguments either, and solved that problem with a template parameter (well, a parameter pack, since there are zero or more).

Just do the same for the return type!

template <typename ReturnType, typename... Args>
class Sample
{
public:
    Sample(Args... args, std::function<ReturnType(Args...)> fnct) :
        _inputBuff(std::forward_as_tuple(args...))

    { }

    std::tuple<Args...>     _inputBuff;
    std::vector<ReturnType> _resultBuff;
};

(live demo)

Upvotes: 10

Related Questions