【问题标题】:function template explicit instantiation extern函数模板显式实例化外部
【发布时间】:2014-02-26 20:38:04
【问题描述】:

我有一个函数,它对许多基本类型都有完全相同的代码。为了节省代码行,我想 declare 将其作为模板并显式地为所有以后使用的类型实例化它once:头文件中的声明和实现 + 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。如果它是extern template void foo&lt;int&gt;();(请参阅接受的答案here)会有所不同,禁止编译器在头文件中实例化一个已经实现的模板.

编辑:

// 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;
}

【问题讨论】:

标签: c++ templates instantiation extern


【解决方案1】:

您的语法在头文件中声明在某处存在 template &lt;class T&gt; T func (T arg); 仍然不允许用户使用该模板函数的代码,但会让模板代码执行此操作(哪个编译器将无法在没有看到模板函数定义的情况下实例化)。

您所指的常见问题解答部分以语法为特色,声明在某处存在某个类X 的模板实例化,而编译器在看到X x = func(X()); 时不应实例化模板,而是将符号未解析,并且让链接器处理它。

【讨论】:

  • 我想让编译器知道有一组函数 template &lt;class T&gt; T func (T arg); 可用,并且链接器能够在 cpp 文件中找到它们的唯一实例化.就像我在通常的 header/cpp 设计中编写了一个正常的重载函数 bib 一样(请参阅我的编辑)。
猜你喜欢
  • 2019-04-15
  • 2011-06-23
  • 2011-10-07
  • 2017-06-11
  • 1970-01-01
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多