Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access a class's member type via an instance of this class?

Tags:

c++

types

class

I don't know why, I was sure that, in C++, if one declares a type alias (via using or typedef) inside a class or struct, like here:

class klasa
{
public:
    using typ = int;
};

Then this type can not only be accessed via the class name, as in here: klasa::typ, but also via an instance of this class, using the dot operator, as in here: klasa k; k.typ.

Apparently, I was mistaken. I try:

class klasa
{
public:
    using typ = int;
};

int main()
{
    klasa k;
    k.typ i = 0;

    return 0;
}

The compiler complains:

ffs.cc: In function ‘int main()’:
ffs.cc:10:7: error: invalid use of ‘using typ = int’
     k.typ i = 0;
       ^

I can only make the compiler shut up if I substitute k.typ i = 0; with:

decltype(k)::typ i = 0;

Thus my question. Did I completely dream up the possibility of accessing class member types through instances of this class, because the only way to access the class's member types is through the class itself and not through objects of this class? Or is it actually true that one can access member types of a class through instances of this class, only one must do this in a different way than by the simple dot operator, and I forgot how to do this correctly?


1 Answers

Did I completely dream up the possibility of accessing class member types through instances of this class, because the only way to access the class's member types is through the class itself and not through objects of this class? Or is it actually true that one can access member types of a class through instances of this class, only one must do this in a different way than by the simple dot operator, and I forgot how to do this correctly?

It's the former. The grammar of the language does not allow expressions where a type is required. You need to use decltype to get at an expression's type.

Perhaps you've confused this with static members or enumerators, which can be accessed using both className:: and objectName. syntax.

like image 123
Angew is no longer proud of SO Avatar answered Oct 18 '25 11:10

Angew is no longer proud of SO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!