C代码是否有任何方法可以判断它是否在乘法快速的架构上编译?是否有一些宏__FAST_MULT__
或在这些架构上定义的东西?
例如,假设您正在实现一个函数,通过shift-and-add方法确定64位整数的汉明权重.有两种最佳算法:一种需要17次算术运算,而另一种只需要12次,但其中一种是乘法运算.因此,如果您在硬件上运行,第二种算法的速度提高了30%,其中乘法所需的时间与添加时间相同 - 但是,在将乘法实现为重复加法的系统上,要慢得多.
因此,在编写这样的函数时,能够在编译时检查是否是这种情况并在适当时在两种算法之间切换是有用的:
unsigned int popcount_64(uint64_t x) {
x -= (x >> 1) & 0x5555555555555555; // put count of each 2 bits into those 2 bits
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333); // put count of each 4 bits into those 4 bits
x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f; // put count of each 8 bits into those 8 bits
#ifdef __FAST_MULT__
return (x …
Run Code Online (Sandbox Code Playgroud) 请考虑以下代码:
class Foo {
Foo() {}
};
class Bar {
Foo &Foo_ref;
Bar() : Foo_ref() {}
};
Run Code Online (Sandbox Code Playgroud)
按原样编写,我收到错误:
tmp.cc: In constructor Bar::Bar(): tmp.cc:7: error: value-initialization of Foo& Bar::Foo_ref, which has reference type
我试过了我能想到的每一个变化.我究竟做错了什么?如何将引用成员初始化为新实例?我现在使用const指针而不是引用作为解决方法,但我更喜欢使用引用.