4

这是一些简化的代码来演示我遇到的问题。

我有一个模板函数,我只想编译某些固定的实例。

函数声明如下:

// *** 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++ 和模板语法中应该有比这更优雅的东西。

任何帮助或提示将不胜感激。

4

2 回答 2

5

您需要在标头中声明函数模板:

template <typename T>
T square(T x);

正如您现在所拥有的,您在标头中声明了两个从未定义过的非模板函数。

于 2010-03-23T15:56:44.663 回答
1

如果您想从头文件中隐藏模板,则没有其他方法。您必须具有包装器函数,因为int square (int x);没有与重命名相同的名称,template int square (int x);并且 C++ 没有为您提供更改它的方法。

作为示例,您可以查看名称混合在 Visual Studio 中的不同之处。

于 2012-05-21T21:53:29.100 回答