0

below code compiled fine

template<typename T>
struct foo
{
    static const T value = 1 + foo::value;
};

but this one is error

struct foo
{
    static const int value = 1 + foo::value;
};

and also

template<typename T>
struct foo
{
     static const int value = 1 + foo::value;
};

Error   1   error C2065: 'value' : undeclared identifier    c:\visual studio 2013\projects\consoleapplication2\consoleapplication2\consoleapplication2.cpp  13  1   ConsoleApplication2

i think second case is reasonable anyway

but first one is how it works?

can someone explain this?

hiall
  • 89
  • 5

2 Answers2

2

In the first example there is no static member variable foo::value, there exists only a template for such a variable, it doesn't exist until you actually try to use it. So if you do e.g. foo<int>::value then you will get an error for the first one as well.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    I would add that if OP really call `foo::value` he would get different compilation error as compiler will try to resolve recursive template call of the static field... – W.F. Mar 03 '16 at 07:36
0

You should look Template Instantiation. Template Instantiation is done when try to make an object of that class. First time you compile the program then type of static member value depends on the template argument you pass while instantiating it. In the second case, foo is compiled completely and compiler finds out that value is not declared so reports the error.

Community
  • 1
  • 1
0x0001
  • 525
  • 4
  • 12