i have templated functions in c++11 xcode project , of them have specializations. however, have discovered specializations called in debug builds; if build in release, ignored.
i have created simple example:
special.h
#include <cstdio> struct special { template<typename t> void call(const t&) { puts("not special"); } };
special.cpp
#include "special.h" #include <string> template<> void special::call(const std::string&) { puts("very special"); }
main.cpp
#include "special.h" #include <string> int main() { std::string str = "hello world"; special s; s.call(123); s.call(str); }
you can download project (until somewhere summer of 2013 @ least) reproduce issue if don't want create yourself. first run project debug configuration, run again in release. output expect is:
not special
special
and indeed debug build configuration. however, release, this:
not special
not special
which means specialized implementation of special::call
in special.cpp ignored.
why result inconsistent? should ensure specialized function called in release builds?
your program has ub. explicit specialisation or @ least declaration must visible before being used. [temp.expl.spec]§6:
if template, member template or member of class template explicitly specialized specialization shall declared before first use of specialization cause implicit instantiation take place, in every translation unit in such use occurs; no diagnostic required.
add declaration special.h
:
template<> void special::call(const std::string&);
alternatively, can put specialistation header. however, specialisation no longer template, follows normal function rules , must marked inline
if placed in header.
also, careful function template specialisations have rather specific behaviour, , it's better use overloads specialisations. see herb sutter's article details.
Comments
Post a Comment