Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/46198648/usage-of-void-in-a-comma-separated-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...