プリアンブル: ポインターを整数型に変換したい (アライメントをチェックするなど)。uintptr_t
正しい型のようですが、C++ (または C++11) ではなく、C でのみ保証されています。
次のコードの場合:
#include <stdint.h>
#ifndef I_WONDER_IF_UINTPR_T_IS_DEFINED
typedef unsigned long uintptr_t;
#endif
template <typename T>
bool isAligned(unsigned char* p) ///Checks alignment with respect to some data type
{
return !((uintptr_t) p % sizeof(T));
}
template bool isAligned<uint16_t>(unsigned char* p);
template bool isAligned<uint32_t>(unsigned char* p);
template bool isAligned<uint64_t>(unsigned char* p);
2 つの質問:
- 置いたところに使える魔法と約束の言葉はあり
I_WONDER_IF_UINTPR_T_IS_DEFINED
ますか? - 私はそれを使用
unsigned long
して忘れるべきですか?
生成されたアセンブリ (uintptr_t が利用可能な場合): http://goo.gl/4feUNK
注 1: C++11alignof
の代わりに使用する必要があるsizeof
ことを認識しています 注 2: この議論を認識しています: <cstdint> vs <stdint.h>