Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - pass function by value (?) instead of function pointer?

Sorry if this has been asked before, but I was unable to find it.

So im trying to educate myself about templates and the new C++11 features (mainly lambdas, something I always liked in other languages).

But in my tests I came to something I had no idea it worked, and I'm trying to understand how it works but cant figure it out..

The following code:

template <class Func>
void Test( Func callback ) {
    callback( 3 );
}

void Callback( int i ) {
    std::cout << i << std::endl;
}

int main( int argc, char** argv ) {
    Test( &Callback ); // this I was expecting to work, compiler will see its a pointer to a function
    Test( Callback ); // this also works, but how?!
    return 0;
}

If I understand how templates work, basically they're a scheme for the compiler to know what to build, so the first call Test( &Callback ); I was expecting to work because the compiler will see the template receives a function address and will assume the arguments should be a pointer.

But what is the second call? What is the template assuming it is? A copy of a functio (if that even makes any sense)?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

A function is implicitly convertible to a pointer to itself; this conversion happens pretty much everywhere. Test(Callback) is exactly the same as Test(&Callback). There is no difference. In both cases, Func is deduced to be void(*)(int).

Function pointers are weird. You can find out more about them in "Why do all these crazy function pointer definitions all work?"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...