タプル要素のオフセットを取得するために次のコードを書きました
template<size_t Idx,class T>
constexpr size_t tuple_element_offset() {
return static_cast<size_t>(
reinterpret_cast<char*>(&std::get<Idx>(*reinterpret_cast<T*>(0))) - reinterpret_cast<char*>(0));
}
これは実際には、offsetofマクロの実装に似ています。見栄えは悪いですが、コンパイルして gcc-4.6 で問題なく動作します。
typedef std::tuple<int,char,long> mytuple;
mytuple var = std::make_tuple(4,'c',1000);
char * ptr = reinterpret_cast<char*>(&var);
long * pt = reinterpret_cast<long*>(ptr+tuple_element_offset<2,mytuple>());
std::cout << *pt << std::endl;
「1000」を出力します。
私は constexpr についてあまり知らないので、私の質問は次のとおりです。
- それは合法的なc ++ですか?
- さらに重要なのは、constexpr 関数内で std::get (constexpr ではない) を呼び出すことが許可されているのはなぜですか?
私が constexpr を理解している限り、コンパイラはコンパイル時に式の結果を評価することを強制されるため、実際にはゼロ参照解除は発生しません。