功能模板显式实例外观
function template explicit instantiation extern
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());
时,不应是实例化模板,而是尚未解决符号,让链接器处理并让链接器处理。它。
- 从C++实例化QML
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 建议在运行时将带有类实例的列表从c++导入qml
- 约束和显式模板实例化
- 通过实例理解std::move及其目的
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 正在生成未知类实例
- 从DLL中删除类的实例
- 功能模板显式实例外观
- 如何更改模板实例化的外观,如std::函数中所示