简体   繁体   中英

Compile template class failed by g++ or clang++

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?

GCC and Clang are correct according to the dry letter of the ISO C++ standard:

[temp.expl.spec]/13

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM