c++ - How to properly explicitly instantiate a template class with fully-specialized members? -
let's have following files:
foo.h
namespace ns { template <typename t> class foo { public: foo(); ~foo(); void doit(); }; }
foo.cpp
#include "foo.h" #include <iostream> namespace ns { template <typename t> foo<t>::foo() { std::cout << "being constructed." << std::endl; } template <typename t> foo<t>::~foo() { std::cout << "being destroyed." << std::endl; } template <> void foo<int>::doit() { std::cout << "int" << std::endl; } template <> void foo<double>::doit() { std::cout << "double" << std::endl; } template class foo<int>; template class foo<double>; }
is correct way explicit instantiation, assuming type ever used int or double type parameters? or need declare explicit specialization in header file well?
doing way i've shown works visual studio, coworker has been having problems gcc (although i've checked, , think that's due else, i'll post question anyway)
[temp.expl.spec]/p6 (emphasis mine):
if template, member template or member of class template explicitly specialized that specialization shall declared before first use of specialization cause implicit instantiation take place, in every translation unit in such use occurs; no diagnostic required.
in fact, if combine them inside single tu, both clang , gcc will issue error. need declare these explicit specializations.
and since close it, i'll quote [temp.expl.spec]/p7 well, because can:
the placement of explicit specialization declarations function templates, class templates, variable templates, member functions of class templates, static data members of class templates, member classes of class templates, member enumerations of class templates, member class templates of class templates, member function templates of class templates, static data member templates of class templates, member functions of member templates of class templates, member functions of member templates of non-template classes, static data member templates of non-template classes, member function templates of member classes of class templates, etc., , placement of partial specialization declarations of class templates, variable templates, member class templates of non-template classes, static data member templates of non-template classes, member class templates of class templates, etc., can affect whether program well-formed according relative positioning of explicit specialization declarations , points of instantiation in translation unit specified above , below. when writing specialization, careful location; or make compile such trial kindle self-immolation.
Comments
Post a Comment