为什么很明显模板函数实例化不会被内联? [英] Why is it clear that a template function instantiation will not be inlined?

查看:23
本文介绍了为什么很明显模板函数实例化不会被内联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于作为模板参数传递的函数,Ben Supnik 提供的社区维基答案讨论内联实例化函数模板的问题.

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<typename OP>
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);

答案继续这样说(关于最后一行,它实例化了函数模板 do_op):

The answer goes on to say this (in regards to the final line, which instantiates the function template do_op):

显然这没有被内联.

我的问题是:为什么很明显这没有被内联?

My question is this: Why is it clear that this is not getting inlined?

推荐答案

他所说的(我认为)是 add 函数没有被内联.换句话说,编译器可能会像这样内联 do_op:

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);

但它也不会像这样内联 add :

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();
}

这里,编译器无法知道callThroughPointer 会调用f1 还是f2,因此它无法内联callThroughPointer 中的 >f1 或 f2.

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();
}

这里,编译器可以证明f永远是f1,所以允许将f1内联到callThroughPointer2代码>.(这并不意味着它内联f1...)

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…)

同样,在您在帖子中引用的示例中,编译器可以证明func_ptr 在对do_op 的调用中始终是add,所以允许内联add.(这并不意味着它内联add...)

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…)

这篇关于为什么很明显模板函数实例化不会被内联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆