C ++使用的模板,以避免检查布尔编译 [英] C++ use templates to avoid compiler from checking a boolean

查看:108
本文介绍了C ++使用的模板,以避免检查布尔编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个函数:

Let's say I have a function:

template <bool stuff>
inline void doSomething() {
    if(stuff) {
        cout << "Hello" << endl;
    }
    else {
        cout << "Goodbye" << endl;
    }
}

和我叫它是这样的:

doSomething<true>();
doSomething<false>();

这将普林了:

Hello
Goodbye

我真正知道是否该编译器完全优化呢?
当我打电话与真正的模板函数,它会创建只输出你好,并避免了if语句和code函数再见?

What I'm really wondering is does the compiler fully optimize this? When I call the templated function with true, will it create a function that just outputs "Hello" and avoids the if statement and the code for "Goodbye"?

这将是这一个巨大的功能真正有用的我刚写的那个应该是非常优化,避免因为很多不必要的if语句检查成为可能。我有一个很好的感觉的那样,至少在发行与优化建设如果不能在调试建立与没有优化。

This would be really useful for this one giant function I just wrote that's supposed to be very optimized and avoid as many unnecessary if statement checks as possible. I have a very good feeling it would, at least in a release build with optimizations if not in a debug build with no optimizations.

推荐答案

免责声明:没有人可以保证什么

Disclaimer: Noone can guarantee anything.

这是说,这是任何编译器这样一个明显和易于优化,这是相当肯定地说,它会被优化掉,除非优化器实际上是无用的。

That said, this is such an obvious and easy optimization for any compiler, it's quite safe to say that it will be optimized away, unless the optimizer is practically useless.

由于你的真与假是常量,你明确地建立在每个类别的公然明显枯枝,编译器应该优化它了。

Since your "true" and "false" are CONSTANTS, you are unambiguously creating a blatantly obvious dead branch in each class, and the compiler should optimize it away.

在换句话说,如果你的编译器无法优化,这种讨论是至少你的问题。

In other words, if your compiler cannot optimize this, this discussion is the least of your problems.

在尚未换句话说,你的直觉是正确的:虽然不能保证能对每一个编译器进行,我绝不会使用编译器不能执行枯枝去除简单的优化。 (在发布版本当然)。

In yet other words, your gut feeling is correct: while no guarantees can be made on each and every compiler, I would never use a compiler incapable of performing the simplistic optimization of dead branch removal. (In release builds of course).

总之,使用它。任何现代的优化编译器将优化它扔掉,因为它实在太明目张胆的枯枝忽视。如果没有优化,我会改变编译器现在。

如果你正在写任何性能关键code,你必须依靠,至少在一定程度上,编译器优化,这是最基本的一个存在。

If you are writing any kind of performance-critical code, you MUST rely, at least to some extent, to compiler optimizations, and this is one of the most basic there is.

这篇关于C ++使用的模板,以避免检查布尔编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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