ustulation
ustulation

Reputation: 3750

Why does member function of class template get constructed in this case?

struct ABC {};

template<typename T>
class DEF
{
   void f0(typename T::ab) {} //ERROR
   void f1() {typename T::ab var;} //Fine
};

DEF<ABC> obj;

I thought if I don't use a particular member function of a class template it never gets constructed by the compiler. Hence as expected even with f1() the code compiles fine because obj never uses it. Why does the presence of f0() result in compile error? I'm not using that too.

{MinGW g++ 4.7.2, Windows 7}

Upvotes: 0

Views: 85

Answers (3)

AnT stands with Russia
AnT stands with Russia

Reputation: 320371

Each member function declaration is an integral part of the entire class definition. Meanwhile, member function definition is a completely independent entity, which is not a part of class definition.

When you instantiate an object of some specialized template class, you are instantiating the entire definition of that class, i.e. you are "using" the entire definition of that class, which in turn means that you are "using" all member declarations as well.

Below is the part that turns into the class definition in your case, once the template is specialized

template<typename T>
class DEF
{
   void f0(typename T::ab);
   void f1();
};

All the above has to be valid for the given value of T in order for the class definition to be usable, i.e. in order to be able to declare DEF<ABC> obj;.

Meanwhile the definition of

template<typename T> void DEF<T>::f1() 
{
  typename T::ab var;
}

is an independent template. It is only instantiated if you use f1.

Upvotes: 4

dchhetri
dchhetri

Reputation: 7136

It is because of lazy instantiation. When you do DEF<ABC> obj. The compiler will look at the prototype/definition of the class DEF. Thus void f0(typename T::ab) fails because ab doesn't exist and you get a compile error.

The reason why you don't get a compiler error for void f1(){typename T::ab var} is because it has never been instantiated. If you do obj.f1(), you will see that it will error out the same message as the one associated with DEF::f0.

Upvotes: 2

Nicholaz
Nicholaz

Reputation: 1429

The compiler at least needs a valid prototype for the function to then determine if it is used (and then subsequently compile the body or not).

Upvotes: 2

Related Questions