how to reference a typedef within a class with an instance of such class?

c++, static, typedef

Solution

You have to use `A::t` instead of `a.t` because the typedef is like `static` and `a` is an instance of `A`.

EDIT: In contrast to what I said above, it is not always "like `static`". For static members, there is this special rule:

A static member s of class X may be referred to using the qualified-id expression X::s; it is not necessary to use the class member access syntax (5.2.5) to refer to a static member. A static member may be referred to using the class member access syntax, in which case the object expression is evaluated. [ Example:

struct process {
  static void reschedule();
};
process& g();

void f() {
  process::reschedule(); // OK: no object necessary
  g().reschedule();      // g() is called
}

Since a `typedef` is not a static member, this syntax is invalid.

Given the instance `a` and not this syntactic sugar, the only way to get `t` is to get the type of it. C++11 gives us a tool for that:

typedef decltype(a) a_type;
f<a_type::t>();
a_type::t somevar;

However, I see no practical use of it (ok, maybe in macros, but everyone knows that templates are better).

Problem

Is there a way to get this code work, just like it does when calling a static function with the dot notation? ``` struct A{ static void f(){ } typedef int t; }; template<typename T> void f(){} int main(){ A a; a.f(); //legit f<a.t>(); //‘a’ cannot appear in a constant-expression, ‘.’ cannot appear in a constant-expression a.t somevar; //invalid use of ‘A::t’ f<a::t>(); //‘a’ cannot appear in a constant-expression a::t somevar; //‘a’ is not a class, namespace, or enumeration } ``` EDIT: Guys, please read the question and test your code before posting. The point here is NOT to use `A::t` but "invoke" `t` through an instance of `A`, like you can do with static methods.

Original source