我编写了以下代码来获取元组元素的偏移量
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 ,编译器被迫在编译时评估表达式的结果,因此在实践中不会发生零解引用。