成员变量的C ++类型名

Any*_*orn 5 c++ variables member typename

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

struct C { int value ; };

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

谢谢

Joh*_*itb 5

仅当您擅长处理函数中的类型时

struct C { int value ; };

template<typename T, typename C>
void process(T C::*) {
  /* T is int */
}

int main() {
  process(&C::value); 
}
Run Code Online (Sandbox Code Playgroud)

它不适用于参考数据成员。C++0x 将允许decltype(C::value)更轻松地做到这一点。不仅如此,它还decltype(C::value + 5)允许decltype. Gcc4.5已经支持了。


GMa*_*ckG 5

不在C ++ 03中。C ++ 0x引入了decltype

typedef decltype(C::value) type;
Run Code Online (Sandbox Code Playgroud)

但是,某些编译器具有typeof扩展名:

typedef typeof(C::value) type; // gcc
Run Code Online (Sandbox Code Playgroud)

如果您对Boost没问题,他们可以提供一个

typedef BOOST_TYPEOF(C::value) type;
Run Code Online (Sandbox Code Playgroud)