C++ typename of member variable
Is it possible t开发者_JAVA百科o get typename of a member variable? For example:
struct C { int value ; };
typedef typeof(C::value) type; // something like that?
Thanks
Not in C++03. C++0x introduces decltype
:
typedef decltype(C::value) type;
Some compilers have a typeof
extension, though:
typedef typeof(C::value) type; // gcc
If you're okay with Boost, they have a library for it:
typedef BOOST_TYPEOF(C::value) type;
Only if you are fine with processing the type in a function
struct C { int value ; };
template<typename T, typename C>
void process(T C::*) {
/* T is int */
}
int main() {
process(&C::value);
}
It won't work with reference data members. C++0x will allow decltype(C::value)
to do that more easily. Not only that, but it allows decltype(C::value + 5)
and any other fancy expression stuff within the decltype
. Gcc4.5 already supports it.
May not be exactly what you're looking for, but a possibly better solution in the long run:
struct C {
typedef int type;
type value;
};
// now we can access the type of C::value as C::type
typedef C::type type;
This isn't exactly what you want, but it does allow us to hide the implementation type of C::value
so that we can later change it, which is what I suspect you're after.
It depends what you need to do with it but you would do something like:
#include <iostream>
using namespace std;
struct C
{
typedef int VType;
VType value;
};
int main()
{
C::VType a = 3;
cout << a << endl;
}
精彩评论