相关疑难解决方法(0)

C++ Compile-Time offsetof模板内部

我需要使用offsetoftemplate一个成员选择.如果您原谅尴尬的语法,我想出办法:

template <typename T,
          typename R,
          R T::*M
         >
constexpr std::size_t offset_of()
{
    return reinterpret_cast<std::size_t>(&(((T*)0)->*M));
};
Run Code Online (Sandbox Code Playgroud)

用法并不完美(最好烦恼):

struct S
{
    int x;
    int y;
};

static_assert(offset_of<S, int, &S::x>() == 0, "");
static_assert(offset_of<S, int, &S::y>() == sizeof(int), "");
Run Code Online (Sandbox Code Playgroud)

constexpr形式更容易使用:

template <typename T, typename R>
std::size_t offset_of(R T::*M)
{
    return reinterpret_cast<std::size_t>(&(((T*)0)->*M));
};
Run Code Online (Sandbox Code Playgroud)

明显的缺点是它不是在编译时完成的(但更容易使用):

int main()
{
    std::cout << offset_of(&S::x) << std::endl;
    std::cout << offset_of(&S::y) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找的是语法constexpr品种,但仍然完全编译时间; 但是,我无法想出它的语法.我也很满意offset_of<&S::x>::value(就像其他类型特征一样),但无法弄清楚它的语法魔法.

c++ offsetof type-traits c++11

14
推荐指数
1
解决办法
6219
查看次数

成员变量的C ++类型名

是否可以获取成员变量的类型名?例如:

struct C { int value ; };

typedef typeof(C::value) type; // something like that?
Run Code Online (Sandbox Code Playgroud)

谢谢

c++ variables member typename

5
推荐指数
2
解决办法
3439
查看次数

标签 统计

c++ ×2

c++11 ×1

member ×1

offsetof ×1

type-traits ×1

typename ×1

variables ×1