Home explicit instantiation of static variable of a template class in different translation units
Reply: 0

explicit instantiation of static variable of a template class in different translation units

user1089
1#
user1089 Published in April 27, 2018, 6:52 am

I was working with a template class that contains a static variable. The structure of code is as follows.

Header.h

template<class T> class Foo
{
public:
    static int count;
    Foo() {
        count++;
    }
    void printCount() {
        cout << count << endl;
    }
};
template<class T> int Foo<T>::count;

Source.cpp

#include "Header.h"
template<> int Foo<int>::count = 5;

main.cpp

#include <iostream>
using namespace std;
#include "Header.h"
int main()
{
    Foo<int> obj1;
    Foo<int> obj2;
    obj1.printCount();
    obj2.printCount();
    return 0;
}

the output on xcode8.3.3 is:

 7
 7

whereas the output on Visual Studio 2015 is:

2
2

i.e. the specific instantiation overrides the generic instantiation in xcode8.3.3 but not in Visual Studio 2015. Could someone explain this difference in behavior? Thanks in advance.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.367151 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO