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
237 views
in Technique[技术] by (71.8m points)

c++ - Construction of a void Type?

I was given a piece of code that uses void() as an argument. The code doesn't compile... obviously?

Can we instantiate anything of type void? I believed the answer was no, with the exception of a void*. For example:

  1. Writing the function void askVoid(void param) {} errors:

A parameter may not have void type

  1. Writing the function void askNaught() {} and calling it with askNaught(void())` errors:

error C2660: takeNaught: function does not take 1 arguments

  1. Writing the templatized function template <typename T> void takeGeneric(T param) {} and calling it with takeGeneric(void()) errors:

error C2893: Failed to specialize function template void takeGeneric(T)

  1. Declaring void voidType errors:

Incomplete type is not allowed

  1. Declaring auto autoVoid = void() errors:

Cannot deduce auto type

  1. Declaring void* voidPtr works fine, but remove_pointer_t<decltype(voidPtr)> decltypeVoid errors:

error C2182: decltypeVoid: illegal use of type void

That's it, right? There is no place for void() in C++ is there? This is just bad code I've been given, right?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

C++ (and I say C++, not C) allows (§6.6.3 comma 2) functions with void return type to return a void expression, that is:

void foo() { return void(); }

But notice it is not constructing a temporary void!


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

...