user129506
user129506

Reputation: 337

Static variable in template undefined

Why isn't this code working and giving an "undefined max" ?

#include <iostream>
using namespace std;

template<typename T>
struct Foo {
  static T const max;
};

template<> struct Foo<int> { // Specialization
    static int max; 
};

template<typename T> T const Foo<T>::max = 22;

template struct Foo<int>;

int main() {

    struct Foo<int> ma;
    cout << ma.max;

    return 0;
}

I defined the static variable and I instantiated the template (I believe the explicit instantiation is useless here).

What's wrong?

Upvotes: 1

Views: 72

Answers (1)

Jarod42
Jarod42

Reputation: 218323

template<typename T> T const Foo<T>::max = 22; is the definition of the general case, not for the specialization.

You have also to define int Foo<int>::max = 22; for the int specialization.

Upvotes: 1

Related Questions