存在库源可用的情况,并且它通常必须支持变量参数,但实际上这些参数通常是常量.
然后可以通过对常量参数的特殊处理来优化事物(例如,使用静态数组而不是堆分配),但为此必须首先确定某些事物是否是常量(或者可能定义一些宏,但它不太方便).
所以这是一个有效的实现.
更新:也在这里:http://codepad.org/ngP7Kt1V
更新:这是一个更符合预期用途的更新.if(N==0)如果N不是0 ,编译器将不会为分支生成任何代码.如果需要,我们可以切换到完全不同的数据结构.当然它不完美,但这就是我发布这个问题的原因.
#include <stdio.h>
struct chkconst {
struct Temp { Temp( int x ) {} };
static char chk2( void* ) { return 0; }
static int chk2( Temp ) { return 0; }
};
#define is_const_0(X) (sizeof(chkconst::chk2(X))<sizeof(int))
#define is_const_0i(X) (sizeof(chkconst::chk2(X))>sizeof(char))
#define is_const(X) is_const_0( (X)^((X)&0x7FFFFFFF) )
#define const_bit(X1,bit) (is_const_0i((X1)&(1<<bit))<<bit)
#define const_nibl(X1,bit) const_bit(X1,bit) | const_bit(X1,(bit+1)) | const_bit(X1,(bit+2)) | const_bit(X1,(bit+3))
#define const_byte(X1,bit) const_nibl(X1,bit) | const_nibl(X1,(bit+4))
#define const_word(X1,bit) const_byte(X1,bit) …Run Code Online (Sandbox Code Playgroud) 是否可以编写一个类,使其有效:
Foo a;
Foo b = 0;
Foo c = b;
Foo d(0);
Foo e(1);
Foo f = Foo(1);
Run Code Online (Sandbox Code Playgroud)
但这些不是:
int x;
Foo a = x;
Foo b = 1;
Foo c = 2;
//etc
Run Code Online (Sandbox Code Playgroud)
从本质上讲,我的规则是"一个常量0可以隐式转换为a Foo,但没有其他值"