C++ 具有显式模板实例化的未解析外部。声明语法是什么?

C++ 具有显式模板实例化的未解析外部。声明语法是什么?,c++,templates,instantiation,unresolved-external,C++,Templates,Instantiation,Unresolved External,这里有一些简化的代码来演示我遇到的问题 我有一个模板函数,我只希望编译某些固定的实例化 函数声明包括: // *** 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 <

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

我有一个模板函数,我只希望编译某些固定的实例化

函数声明包括:

// *** 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);
定义如下:

// *** 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);
/***template.cpp***
#包括“template.h”
//(模板定义在代码中而不是在头文件中)
模板
T平方(T x)
{
返回x*x;
}
//显式实例化
模板整数平方(整数x);
模板浮动方块(浮动x);
并且,示例用途是:

// *** main.cpp ***

#include <iostream>
using namespace std;

#include "template.h"

int main (void)
{
    cout << square(2) << endl;
    cout << square(2.5) << endl;
}
/***main.cpp***
#包括
使用名称空间std;
#包括“template.h”
内部主(空)
{

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

template <typename T>
T square(T x);
模板
T平方(tx);

现在,您在头文件中声明了两个从未定义的非模板函数。

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


您可以以签出为例。

但这意味着您有更多的可用类型,而不仅仅是双精度和双精度int@Ronny:如果您尝试使用源文件中提供显式实例化的类型以外的任何类型实例化模板,编译将失败。如果声明中没有明确的类型,则编译将失败记录函数模板以详细说明它可以实例化的类型的想法。不同的源文件(main.cpp)如何+标题知道显式实例化吗?链接时会出现错误-可能不是很有帮助。您可以使用描述性静态断言定义模板函数-这样错误不会延迟到链接阶段。感谢到目前为止的评论,但请注意,我的问题不是关于模板函数g一般来说,但特别是关于显式模板函数实例化(例如,虽然在我的例子中不相关,但此类函数可能在库中提供,但不被调用;显式实例化强制编译器生成所需的代码)我不希望在头文件中声明模板,因为模板只在特定的源文件中定义(它是“伪私有的”)。