Lor*_*ins 15 c++ template-specialization
假设我的代码以这种方式构建:
那么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;
};
Run Code Online (Sandbox Code Playgroud)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;
}
Run Code Online (Sandbox Code Playgroud)我的前提条件是我只会在cpp文件中使用特定的特化,所以我不必处理链接器问题.我知道这不适用于cpp2.cpp包含header1.h并试图仅使用use_case<int>或重新定义implementation<int>违反ODR的文件.所以我要问的是这个代码是否类似于它的线性形式(一个版本,其中所有内容都被放入一个符合顺序的单个cpp文件中)(显然)编译得很好.
是的,只要在同一个翻译单元中使用它,这就是格式良好的.
请记住,#include如果将引用的文件逐字插入到翻译单元中,则效果如此.
这就是现在的样子#include.
由此,我们可以得出几个结论:
每个C++翻译单元都是一个虚拟文件.
因此,格式良好的翻译单元中的每个专业化都在定义它的同一翻译单元中引用.
QED