Zereges
Zereges

Reputation: 5209

c++11: void in template arguments

I was implementing some stuff in C++, and I came across a situation, I did not know how to handle properly. Consider following example

template<typename F>
struct function_wrapper;

template<typename Return, typename... Input>
struct function_wrapper<Return(Input...)>
{
    function_wrapper(/*...*/) = /* ... */
    std::tuple<Input...> input_args;
    Return return_value;

    void first_calculate_result() { return_value = somehow_manipulate(input_args); }
    Return operator()() { return return_value; }
}

Now, obvious usage is like this

my_function<int(double)> stored_fnc(5.5);
stored_fnc.first_calculate_result();
/* something maybe else */
std::cout << "Result is: " << stored_fnc() << std::endl;

Everything works as expected, as long as function's return type is not void.

My question is, do I have to write partial specification for my_function<void(Input...)>, where I would omit all Return stuff, or is there an easier way? Moreover, why does the C++ standard does not allow me to define void variables?

Upvotes: 2

Views: 2807

Answers (1)

Barry
Barry

Reputation: 303107

do I have to write partial specification for my_function<void(Input...)>...

As written, yes. You are saving the return value from your call in a variable, so there's no way around that. However, you could simply not write your function_wrapper that way, and have operator() simply return:

Return operator()() { return somehow_manipulate(input_args); }

You're allowed to write code like that even if Return is void and somehow_manipulate is a void function. That's how std::function<R(Args...)> is implemented. There's no special case for void.

why C++ standard does not allow to define void variables?

Because void is not a value. A void function doesn't return something of type void, it doesn't return anything. It's uniquely nothing. It is emptiness. It is the Buddhist ideal. You cannot have something of nothing.

Upvotes: 3

Related Questions