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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With