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

c++ - difference between void(int) & void (*)(int)

I know void (*)(int) is to function pointer but what is void(int)?

It's used for std::function template.

Say I have a function void fun(int){} : decltype(&fun) gives void(*)(int) but decltype(fun) gives void(int)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If T is a type, then T* denotes the type "pointer-to-T".

The type void(int) is a function type, it's the type of a function taking one int and returning void. For example, it is the type of f if f is declared as void f(int);

If T = void(int), then T* is spelled void(*)(int), so the latter is the type of a function pointer. You can also form a reference to a function, which is T& = void(&)(int); this is occasionally more useful (e.g. you can take the address of a function lvalue).


Aside note: Function lvalues decay to their function pointer very easily. You can call a function either via a function lvalue or via a function pointer. When used as an operand for the indirection operator (*), the function value decays, so you can dereference the pointer again and again:

printf("Hello world
");        // OK
(*printf)("Hello world
");     // also OK
(****printf)("Hello world
");  // four-star programmer

Some of the only times that a function does not decay is when used as the operand of the address-of operator, or when bound to a reference:

void f(int);          // our example function

void(*p1)(int) = &f;  // no decay of "f" here
void(*p2)(int) = f;   // "f" decays
void(&r1)(int) = f;   // no decay of "f" here

void g(void(&callback)(int), int n) {
  callback(n);
}
g(f, 10);             // no decay of "f" here

template <typename F, typename ...Args>
decltype(auto) h(F&& callback, Args&&... args) {
    return std::forward<F>(callback)(std::forward<Args>(args)...);
}
h(f, 10);             // no decay of "f" here

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

...