Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of `void()` in a comma-separated list?

Tags:

c++

I was looking into a piece of code written by others when I saw this:

a(), void(), b(); 

where both a and b are instances of a user-defined template class, which is intended to act like a function by overloading operator() that returns the calling instance itself.

Part of the class:

template <typename T> class SomeClass{     public:     SomeClass& operator()(void);     const SomeClass& operator()(void) const; } 

The return statements for both overloads are the following:

template <typename T> SomeClass<T>& SomeClass<T>::operator()(void){     // do stuff     return *this; }  template <typename T> const SomeClass<T>& SomeClass<T>::operator()(void) const{     // do stuff     return *this; } 

What does the void() between them do? I feel it strange.

like image 220
iBug Avatar asked Sep 13 '17 13:09

iBug


1 Answers

The void() prevents an overloaded operator, from being called (where one of the parameters is of the type SomeClass<T>), as such an overload can't have a parameter of type void.

You will most often see this used in templates, and is used in variadic pack expansions:

// C++11/14: int unpack[] = {0, (do_something(pack), void(), 0)...}; // C++17 (fold expression): (void(do_something(pack)), ...); 

Where an overloaded operator, could ruin the sequencing guarantees of the language.

like image 159
Simple Avatar answered Oct 07 '22 16:10

Simple