说我有我的代码结构是这样的:在这种情况下,在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; }
我的前提是,我只在cpp文件中使用特定的专门化,所以我不必处理链接器问题。 我知道这将不适用于包括header1.h
的cpp2.cpp
文件,并试图仅使用use_case<int>
或重新定义违反ODR的implementation<int>
。所以我问的是这个代码是否类似于它的linear form(一个版本,其中一切都被放入一个单一的CPP文件与一致的顺序),(显然)编译好。
你可以使用'extern'模板来达到这个目的。 –
@KerrekSB我被内联命名空间带走了。假设我没有C++ 11代码(如给出的)生病? –
你在寻找什么额外的细节? – Barry