相关疑难解决方法(0)

显式实例化的类模板中的自动构造函数

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)

c++ templates c++11

9
推荐指数
1
解决办法
626
查看次数

标签 统计

c++ ×1

c++11 ×1

templates ×1