Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why class forward declaration is not allowed in function scope?

Below code works fine:

template<typename T> class X {};
class A;  // line-1
void foo();  // line-2
int main ()
{
  X<A> vA;
}
class A {};
void foo() {}

Let line-1 and line-2 are moved inside main(). The function doesn't get affected but the class A forward declaration doesn't work and gives compiler error:

error: template argument for template<class T> class X uses local type main()::A

like image 708
iammilind Avatar asked Feb 19 '26 21:02

iammilind


1 Answers

What you can observe is happening because, in C++, you can define classes inside functions. So, if you place class A; in main, you are forward-declaring a class in scope of this function (i.e. class main::A), not in global scope (class A).

Thus, you are finally declaring an object of type X with a template argument of undefined class (X<main::A>).

like image 175
Krizz Avatar answered Feb 21 '26 15:02

Krizz