首页 > 解决方案 > 这个模板有什么作用?

问题描述

在 llvm 源代码llvm/IR/PassManager.h中有这个模板(为简洁起见,已删除注释):

struct alignas(8) AnalysisKey {};
struct alignas(8) AnalysisSetKey {};
template <typename IRUnitT> class AllAnalysesOn {
public:
  static AnalysisSetKey *ID() { return &SetKey; }

private:
  static AnalysisSetKey SetKey;
};

template <typename IRUnitT> AnalysisSetKey AllAnalysesOn<IRUnitT>::SetKey;

编辑:我只对此感到困惑:template <typename IRUnitT> AnalysisSetKey AllAnalysesOn<IRUnitT>::SetKey;

我熟悉为类或函数使用模板。上面的用法看起来很不一样。模板定义后面不是类或函数,而是结构体和类成员变量。任何对它的作用或为什么以这种方式编写的洞察力都将不胜感激。

标签: c++templatesllvm

解决方案


SetKey是一个静态数据成员,所以在这一行

template <typename IRUnitT> AnalysisSetKey AllAnalysesOn<IRUnitT>::SetKey;

您正在提供该变量的定义,以便在使用此模板时可以将内存分配给静态变量。

如果您使用的是 C++17,则此行可以写为:

static inline AnalysisSetKey SetKey;

然后你确实需要写下你很难理解的那一行。


推荐阅读