我template<bool VAR> struct Obj
在头文件(obj.h
)中声明了一个模板,带有显式自动移动构造函数(= default
).
// obj.h
#pragma once
#include <vector>
template<bool VAR>
struct Obj {
std::vector<int> member;
Obj(int m): member(m) { }
Obj(Obj&&) = default;
int member_fun() const;
};
extern template struct Obj<false>;
extern template struct Obj<true>;
Run Code Online (Sandbox Code Playgroud)
模板的成员函数在另一个文件(obj.cpp
)中定义,并显式模板化实例化:
// obj.cpp
#include "obj.h"
template<bool VAR>
int Obj<VAR>::member_fun() const {
return 42;
}
template struct Obj<false>;
template struct Obj<true>;
Run Code Online (Sandbox Code Playgroud)
然后从主文件(main.cpp
)中使用此模板:
// main.cpp
#include <utility>
#include "obj.h"
int main() {
Obj<true> o1(20); …
Run Code Online (Sandbox Code Playgroud)