模板显式实例化是如何工作的



我很难理解使用extern说明符的模板显式实例化。这是我的例子";

//power.h

template <typename T>
class Power
{
public:
T operator()(T const& x) {return x * x;}
};

//power.cpp

#include "power.h"
template
class Power<int>;

//mathlib.h

class Square
{
public:
Square(int);
inline int side()const { return side_;}
int surface()const;
int perim()const;
private:
int side_{};
};

//mathlib.cpp

#include "mathlib.h"
#include "power.h"
extern template class Power<int>;
Square::Square(int x) :
side_(x)
{}
int Square::surface() const
{
return Power<int>{}(side_);
}
int Square::perim() const
{
return side_ * 4;
}

//physiqlib.h

class Planet
{
public:
Planet(int);
int velocity()const;
private:
int veloc_{};
};

//physiqlib.cpp

#include "physiqlib.h"
#include "power.h"
extern template class Power<int>;

Planet::Planet(int v) :
veloc_(v)
{}
int Planet::velocity()const
{
return Power<int>{}(veloc_);
}

//main.cpp

#include <iostream>
#include "mathlib.h"
#include "physiqlib.h"
#include "power.h"
int main()
{
Square sq{7};
std::cout << "side: " << sq.side() << 'n';
std::cout << "surface: " << sq.surface() << 'n';
std::cout << "perim: " << sq.perim() << 'n';
std::cout << 'n';
std::cout << "Planet name: Earthn";
Planet plEarth(150000);
std::cout << "velocity: " << plEarth.velocity() << 'n';
std::cout << "ndone!n";
}
  • 当我编译程序时,它运行良好,并给出正确的结果,但我想知道Explicit instantiation是否就是这样工作的?

  • 我很抱歉写了整个程序,但我只是想展示一下我是如何使用它的

  • 为了简洁起见,我还举了一个任意的例子,并从标题中删除了包含保护。

  • 请指导我是否走在正确的道路上,尤其是我在论坛上搜索过,我仍然有点困惑。

**如果我从生成中间文件的终端编译程序:g++ -S -save-temps main.cpp physiqlib.cpp power.cpp mathlib.cpp为什么我在每个*.ii中都得到模板类Power的定义?像这样的东西:

//mathlib.ii

# 1 "mathlib.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "mathlib.cpp"
# 1 "mathlib.h" 1

class Square
{
public:
Square(int);
inline int side()const { return side_;}
int surface()const;
int perim()const;
private:
int side_{};
};
# 2 "mathlib.cpp" 2
# 1 "power.h" 1

template <typename T>
class Power
{
public:
T operator()(T const& x) {return x * x;}
};
# 3 "mathlib.cpp" 2
extern template class Power<int>;
Square::Square(int x) :
side_(x)
{}
int Square::surface() const
{
return Power<int>{}(side_);
}
int Square::perim() const
{
return side_ * 4;
}
  • 这是否意味着类模板Power只定义但尚未实例化,而实例化class Power<int>在其他地方?

  • 如果我是正确的,新标准是否可以使用这种技术来避免模板代码膨胀?

非常感谢!

我想知道显式实例化是否就是这样工作的?

是。

为什么我在每个*.ii中都得到了模板类Power的定义?

*.ii文件是预处理阶段的结果。与模板实例化无关。

这是否意味着类模板Power只定义但尚未实例化,而实例化类Power在其他地方?

是的,调用return Power<int>{}(side_);不进行任何隐式实例化

如果我是正确的,新标准是否可以使用这种技术来避免模板代码膨胀?

它可能会减少一些,节省编译时间,因为它只实例化了一次。即使在单个翻译单元中,多个实例化仍可能发生代码膨胀。

class_template#Explicit_instantation的更多详细信息

最新更新