C ++编译时常数检测 [英] C++ compile-time constant detection

查看:135
本文介绍了C ++编译时常数检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些情况下,一个库源代码是可用的,它必须支持一般的变量参数,但实际上这些参数通常是常量。

There're cases when a library source is available, and it has to support variable parameters in general, but in practice these parameters are commonly constants.

可以通过对常量参数(例如使用静态数组而不是堆分配)的特殊处理来优化事物,但是为了它必须首先确定某事是否是常数(或者可能定义一些宏,但不太方便)。

Then it may be possible to optimize things by special handling of constant parameters (eg. use static arrays instead of heap allocation), but for that its necessary to determine whether something is a constant first (or maybe define some macros, but its less convenient).

这里是一个有效的实现。

So here's a working implementation.

更新:也在这里: http://codepad.org/ngP7Kt1V


  1. 这真的是一个有效的C ++?

  2. 有没有办法摆脱这些宏? (is_const()不能是一个函数,因为函数依赖将不会在数组大小表达式中工作;也不能是一个模板,因为它不会接受一个变量参数。)

更新:此更新中包含更多类似预期用途的更新。
编译器不会为<$​​ c $ c> if(N == 0)分支创建任何代码 N 不是0.
同样的方式,如果我们想要,我们可以切换到完全不同的数据结构。
确定它不完美,但这是为什么我发布了这个问题。

Update: Here's an update with something more like intended usage. The compiler won't generate any code for the if(N==0) branch if N is not 0. Same way we can switch to completely different data structures if we want. Sure its not perfect, but that's why I posted this question.


 #include <stdio.h>


推荐答案

GCC,使用 __ builtin_constant_p 告诉你某个东西是否是编译时常量。该文档包括例如

If you're working with GCC, use __builtin_constant_p to tell you whether something is a compile time constant. The documentation includes examples like

static const int table[] = {
  __builtin_constant_p (EXPRESSION) ? (EXPRESSION) : -1,
  /* ... */
};

这篇关于C ++编译时常数检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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