tobi303 tobi303 - 9 months ago 44
C++ Question

Why instantiation fails for local variable but not for static?

I am trying to find an easy way (with pre C++11, ie no

) to document what requirements a template has on a type to work properly. Maybe there are better ways to do this. However, this is my question:

#include <iostream>

template <typename T> struct Foo {
static const int test = sizeof(T::size);

template <typename T> struct DetectAndError {
DetectAndError() { int test = sizeof(T::size); }

struct Bar {};

int main() {
Foo<Bar> x; // NO ERROR ? :/
// std::cout << x.test << std::endl; // ERROR :)
// DetectAndError<Bar> y; // ERROR :)

Why is
Foo<Bar> x;
not an error?
For the other lines I get what I want:

error: 'size' is not a member of 'Bar'

Answer Source

This is because the standard mandates that test will be instantiated only when it is used. Member variables/member functions/static members of a template class aren't instantiated without them being used.

In your case the moment you try to do a x.test compiler tries to find test and subsequently cannot do it as x::size is missing.

The behaviour is pretty much accepted and common and ofcourse as per the standard.