这是一些简化的代码来演示我遇到的问题。
我有一个模板函数,我只想编译某些固定的实例。
函数声明如下:
// *** template.h ***
int square (int x);
double square (double x);
定义是:
// *** template.cpp ***
#include "template.h"
// (template definition unusually in a code rather than header file)
template <typename T>
T square (T x)
{
return x*x;
}
// explicit instantiations
template int square (int x);
template float square (float x);
而且,一个示例用法是:
// *** main.cpp ***
#include <iostream>
using namespace std;
#include "template.h"
int main (void)
{
cout << square(2) << endl;
cout << square(2.5) << endl;
}
尝试编译它会导致链接错误,大致如下:
main.obj : 函数 main 中引用的未解析的外部符号“int square(int)”
我了解问题所在:我的显式模板实例化的函数签名与头文件中的函数签名不匹配。
请问显式模板实例的(前向)声明的语法是什么?我不希望转发声明模板定义,或将模板定义移动到头文件中。
对于它的价值,我确实有一个解决方法,即使用包装函数,将以下内容添加到上述文件中:
// *** template.cpp ***
// ...
// wrap them [optionally also inline the templates]
int square (int x) { return square<> (x); }
double square (double x) { return square<> (x); }
编译并按预期工作。但是,这对我来说似乎是一个黑客行为。在 C++ 和模板语法中应该有比这更优雅的东西。
任何帮助或提示将不胜感激。