Why is it clear that a template function instantiation will not be inlined?

Web Technologies Web Development 2 years ago

0 1 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating
_x000D_ _x000D_ Regarding Function passed as template argument, the community wiki answer provided by Ben Supnik discusses the issue of inlining instantiated function templates. In that answer is the following code: template int do_op(int a, int b, OP op) { return op(a,b,); } int add(int a, b) { return a + b; } int (* func_ptr)(int, int) = add; int c = do_op(4,5,func_ptr); The answer goes on to say this (in regards to the final line, which instantiates the function template do_op): clearly this is not getting inlined. My question is this: Why is it clear that this is not getting inlined?

Posted on 16 Aug 2022, this text provides information on Web Development related to Web Technologies. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago
_x000D_ What he's saying (I think) is that the add function is not getting inlined. In other words, the compiler might inline do_op like this: int c = func_ptr(4, 5); but it won't also inline add like this: int c = 4 + 5; However, he might be wrong in that simple example. Generally, when you call a function through a pointer, the compiler can't know (at compile-time) what function you'll be calling, so it can't inline the function. Example: void f1() { ... } void f2() { ... } void callThroughPointer() { int i = arc4random_uniform(2); void (*f)() = i ? f2 : f1; f(); } Here, the compiler cannot know whether callThroughPointer will call f1 or f2, so there is no way for it to inline either f1 or f2 in callThroughPointer. However, if the compiler can prove at compile-time what function will be called, it is allowed to inline the function. Example: void f1() { ... } void f2() { ... } void callThroughPointer2() { int i = arc4random_uniform(2); void (*f)() = i ? f2 : f1; f = f1; f(); } Here, the compiler can prove that f will always be f1, so it's allowed to inline f1 into callThroughPointer2. (That doesn't mean it will inline f1…) Similarly, in the example you quoted in your post, the compiler can prove that func_ptr is always add in the call to do_op, so it's allowed to inline add. (That doesn't mean it will inline add…)

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

Important Web Technologies Links