功能模板显式实例外观

function template explicit instantiation extern

本文关键字:实例 外观 功能      更新时间:2023-10-16

i具有一个函数,该函数具有许多基本类型的代码完全相同。要保存代码行,我想将其作为模板声明 ,并明确对所有以后使用的类型 asher :在header文件和实现中声明 CPP文件中的明确实例化(设计与编写普通功能围嘴相同)。

我的方法是:

// header.h
template <class T> T func (T arg);

// header.cpp
#include "header.h"
template <class T> T func (T arg)
{
    // implementation...
}
template int func<int> (int arg);
template double func<double> (double arg);

但是,在Parashift上,我发现了这种声明形式:

// header.h
template <typename T> extern void foo();

这里的外部感是什么?与我的方法有何不同?什么是正确的?

也不必声明正常功能extern。如果是 extern template void foo<int>();(请参阅此处的接受答案)会有所不同),禁止编译器可以在标题文件中启用已实现的模板。

编辑:

// header.h
int func (int arg);
double func (double arg);
// header.cpp
#include "header.h"
int func (int arg)
{ ... }
double func (double arg)
{ ... }

不是完全类似/等效于

// header.h
template <class T> T func (T arg);
// here is the question: like above or template <class T> extern T func (T arg); ???
// header.cpp
#include "header.h"
template <class T> T func (T arg)
{ ... }
template int func<int> (int arg);
template double func<double> (double arg);

关于以后的用法

// main.cpp
#include "header.h"
int main ()
{
    // for overloading
    func(20);
    func(20.0);
    func((int)20.0);
    // for template
    func(20); // == func<int>(20)
    func(20.0); // == func<double>(20.0)
    func((int)20.0); // == func<int>((int)20.0)
    func<int>(20.0); // == func<int>((int)20.0)
    return 0;
}

您的语法在标题文件中声明了template <class T> T func (T arg);的某个地方,该语法仍然不会让用户使用该模板函数具有代码,但是让模板代码执行此操作(哪个编译器没有看到模板函数定义就无法实例化。

您所指的FAQ部分的特征是语法,声明某些类别X的模板的实例化和编译器,当看到X x = func(X());时,不应是实例化模板,而是尚未解决符号,让链接器处理并让链接器处理。它。