37

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.

8
  • 8
    No authoritative answer can be given without more context. C++'s grammar is quite complicated. For example 'X *p' could mean either multipliation, or a pointer declaration. You need to provide more context. Sep 13, 2017 at 13:18
  • 2
    Lots of BS in the comments thus far. Comments are not for guessing answers. Correct answer below.
    – Bathsheba
    Sep 13, 2017 at 13:19
  • 2
    This is a valid question and shouldn't be getting downvotes.
    – Simple
    Sep 13, 2017 at 13:20
  • 3
    Actually, @Bathsheba, given the additional context posted, the answer below is not correct. Sep 13, 2017 at 13:20
  • 3
    Where is void() in the posted code? Sep 13, 2017 at 15:14

1 Answer 1

47

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.

17
  • 3
    Wow. I've never heard that someone overloads operator,.
    – iBug
    Sep 13, 2017 at 13:20
  • 5
    @iBug - This is C++, we can overload everything. EVERYTHING! Sep 13, 2017 at 13:21
  • 3
    Not quite yet: the member selection operator and ternary conditional operators being important exceptions. (Although doesn't Stroustrup want to relax the former?)
    – Bathsheba
    Sep 13, 2017 at 13:25
  • 2
    @iBug: fun fact : I did it to manage date/time format depending on the language. (std::cout, lang::fr) << time;. It was funny. :-p
    – Caduchon
    Sep 13, 2017 at 13:28
  • 2
    @Simple Naw, you'd just do void(a()), void(b()) instead.
    – Barry
    Sep 13, 2017 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.