简体   繁体   中英

Dereferencing C++ pointer to type if possible

class Foo {
public:
    static const int BAR = 2;
};

typedef Foo T1;
typedef Foo* T2;

int value1 = T1::BAR;  // This works.
int value2 = T2::BAR;  // This doesn't work.

Can the value of BAR be extracted from T2 ?

I am using c++-11.

I imagine this would be bad practice but am curious if it can be done.

Yes.

You can strip the pointer using traits:

int value2 = std::remove_pointer<T2>::type::BAR;

Or alternatively (since C++14):

int value2 = std::remove_pointer_t<T2>::BAR;

( referencelive demo )

It's not even bad practice, unless there's some more expressive way to achieve your real goal.

You could create an object of type T2 , and access the member BAR , like this:

int value2 = T2{}->BAR;

Note that it's debatable whether dereferencing a null pointer to access a static data member is well-formed or not. Whether this solution is correct or not, I'd suggest using Asteroids With Wings' answer as it is much clearer in expressing the intent of what the code is supposed to achieve.

Lets look at the error first (you should always do that):

<source>:11:14: error: 'T2' (aka 'Foo *') is not a class, namespace, or enumeration
int value2 = T2::BAR;// This doesn't work.

It is quite clear. Foo* is indeed not a class type, namepsace or enumeration.

You can remove the pointer from a type via std::remove_pointer :

int value2 = std::remove_pointer_t<T2>::BAR; // This is awkward, but no error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM