tty6
tty6

Reputation: 1233

Strange use of void in c++ code

Here is some code from a presentation about async tasks in C++

template <class T> class Future<T>{
  //something
  void  foo(std::function<void(T)> cb);    
  //something
};

What does void(T) mean?

Upvotes: 2

Views: 205

Answers (4)

Mike Seymour
Mike Seymour

Reputation: 254461

What does void(T) mean?

That specifies a function type; specifically, a function taking a single parameter of type T, and returning nothing. In general, type specifiers for complex types look like their corresponding variable declarations, but without a variable name:

void f(T); // declare a function
void(T)    // specifier for a function type

int a[42]; // declare an array
int[42]    // specifier for an array type

In this case, the function type is used to specify the signature of the function-call operator of the std::function:

void operator()(T);

so that the function object can be used like a function with that type:

T some_t;
cb(some_t); // usable like a function taking `T`

Upvotes: 7

user2249683
user2249683

Reputation:

void(T) is a function signature (type)

Note the signature is not a pointer to a function, not a pointer to a member function and no lambda:

#include<functional>

void a(int) {}
struct B {
    void f(int) {}
};


int main() {
    std::function<void(int)> fn;
    fn = a;

    B b;
    fn = std::bind(&B::f, b, std::placeholders::_1);

    auto lambda = [](int) {};
    fn = lambda;
}

Upvotes: 1

stripthesoul
stripthesoul

Reputation: 360

The explanation can be as follows based on the C++11 specifications : A parameter list consisting of a single unnamed parameter of non-dependent type void is equivalent to an empty parameter list.

void is not a valid argument type for a function, however T in void(T) is a dependent type, it depends on a template parameter. That way you can have no arguments in the function based on the parameter of the template.

Upvotes: 0

dlf
dlf

Reputation: 9383

cb is a std::function whose operator() takes a T and returns void.

Upvotes: 6

Related Questions