Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef with templates

template<class T> struct A {
    typedef int Int;
    A::Int b; // Line 1 (fails)
    Int c; // Line 2 (compiles)
};

int main(){    
   A<int> x;
   x.c = 13;
}

Errors

error: ISO C++ forbids declaration of ‘Int’ with no type
error: extra qualification ‘A<T>::’ on member ‘Int’
error: expected ‘;’ before ‘b’

Line 1 fails but Line 2 compiles. Why?

like image 928
vij Avatar asked Dec 21 '22 13:12

vij


1 Answers

You need a typename

typename A::Int b;

The typename keyword is required because the member is referred to using a qualified name A::Int.

Int c is fine because no qualified name is used in that case.

14.6/6

Within the definition of a class template or within the definition of a member of a class template, the keyword typename is not required when referring to the unqualified name of a previously declared member of the class template that declares a type. The keyword typename shall always be specified when the member is referred to using a qualified name, even if the qualifier is simply the class template name.

like image 104
Prasoon Saurav Avatar answered Jan 10 '23 17:01

Prasoon Saurav