Say mam mój kod skonstruowany w ten sposób:Czy w tym przypadku można napisać specjalizację szablonów w pliku cpp?
header1.h
template <class T, template<class> class C> struct metafunction { using type = typename C<T>::type; }; inline namespace msn { template <class T> struct implementation; } // uses the *implementation* not defined in the header! template <class T> struct use_case { using type = typename metafunction<T, implementation>::type; };
cpp1.cpp
#include <header1.h> // I'll only need this in this compilation unit, so the // question is: "Is this a good place to define it?" template <> struct implementation<int> { using type = int; }; int main() { using tt = int; // is this point of instantiation OK due to // the existence of a specialization in the same cpp file? using tt = use_case<int>::type; tt var; (void)var; }
Moja Warunkiem jest to, że będę tylko użyj określonej specjalizacji w plikach cpp, więc nie będę musiał zajmować się problemami z linkerem. Wiem, że to nie zadziała dla pliku cpp2.cpp
, w tym header1.h
i próbuje po prostu użyć use_case<int>
lub przedefiniować implementation<int>
, który narusza ODR. Pytam więc, czy ten kod jest analogiczny do jego kodu linear form (wersja, w której wszystko jest umieszczane w jednym pliku cpp z zgodną kolejnością), który (podobno) kompiluje się dobrze.
W tym celu można użyć szablonów "zewnętrznych". –
@KerrekSB Uległe mnie wbudowanym przestrzeniom nazw.Przypuśćmy, że nie mam C++ 11, że kod (jak podano) jest źle sformułowany? –
Jakiego dodatkowego szczegółu szukasz? – Barry