Reputation: 61
I wrote the source code as shown below. ----- sample.h ------
#include <iostream>
template <typename T>
class Sample {
private:
static int foo;
public:
Sample (T number) {
foo = number;}
void display () {
std :: cout << foo << std :: endl;}
};
---- test.cpp --------------
#include "sample.h"
template <> int Sample <float> :: foo;
int main () {
Sample <float> test (100.9);
test.display ();
return 0;
}
I have successfully compiled with Visual Studio 2015 community. However, g++ and clang++ (ubuntu linux 16.04 LTS) failed at linking time. I want to compile with g++ or clang++, so I'd like to do something, I do not get a good idea. Is not it compatible with g++ or clang++ specifications? Are those who are familiar with the compiler, are not you?
Upvotes: 0
Views: 138
Reputation: 170065
GCC and Clang are correct according to the dry letter of the ISO C++ standard:
An explicit specialization of a static data member of a template or an explicit specialization of a static data member template is a definition if the declaration includes an initializer; otherwise, it is a declaration. [ Note: The definition of a static data member of a template that requires default-initialization must use a braced-init-list:
template<> X Q<int>::x; // declaration template<> X Q<int>::x (); // error: declares a function template<> X Q<int>::x { }; // definition
— end note ]
Which when applied to your example means you just provide another declaration, not a definition. And a fix would be to add an initializer:
template <> int Sample <float> :: foo{}; // Default initialize `foo`
Or
template <> int Sample <float> :: foo{0.0}; // Direct initialize `foo` to 0
Or
template <> int Sample <float> :: foo = 0.0; // Copy initialize `foo` to 0
Upvotes: 1