假设我的代码结构是这样的:
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 文件中的特定特化,因此我不必处理链接器问题。 我知道这不适用于 cpp2.cpp
文件包括 header1.h
并试图只使用 use_case<int>
或重新定义 implementation<int>
违反 ODR。所以我要问的是这段代码是否类似于它的linear form (一个版本,其中所有内容都以一致的顺序放入单个 cpp 文件中),(显然)编译得很好。
最佳答案
是的,只要它只在同一个翻译单元中使用,它就是格式正确的。
请记住,#include
的效果就像引用的文件被逐字插入到翻译单元中一样。
这就是 #include
的含义。
由此,我们可以得出几个结论:
每个 C++ 翻译单元都是一个虚拟文件。
因此,格式良好的翻译单元中的每个特化都在定义它的同一翻译单元中被引用。
Q.E.D.
关于c++ - 在这种情况下,可以在 cpp 文件中编写模板特化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39359229/