【发布时间】: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<int>();(请参阅接受的答案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;
}
【问题讨论】:
-
我觉得你可以找到有用的this question and answers
-
@Sigismondo 不,没有真正的帮助
标签: c++ templates instantiation extern