c++ - 如何在源文件中定义模板函数

标签 c++ templates

<分区>

如何在头文件中声明模板函数并在源文件中定义?

// foo.h
template<typename T>
bool foo();

// foo.cpp
template<typename T>
bool foo()
{
    return false;
}

// main.cpp
bool bar = foo<int>();

到目前为止我已经知道了。它编译,但在链接器处失败:“undefined reference to `bool foo()`”

最佳答案

你不能。但是如果你真的想要单独的文件,有一个解决方法:

Foo.tpp

template<typename T> void foo()
{

}

Foo.hpp

#ifndef FOO_HPP_
#define FOO_HPP_

template<typename T>
void foo();

#include "Foo.tpp";

#endif

main.cpp

#include "Foo.hpp"

int main()
{
    foo<int>();
}

基本上,您将实现放在编译器无法识别的单独文件中,并将其包含在 header 的末尾。

关于c++ - 如何在源文件中定义模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50685709/

相关文章:

C++ 模板参数包别名扩展

c++ - 可以显式指定构造函数的模板参数吗?

c++ - 在 Visual Studio C++ 中弃用单个构造函数的正确语法是什么?

c++ - 使用 find 搜索字符串中是否存在空格

c# - 语言不支持

c++ - 怎么了?如何更改 "sum1"顺序?

c++ - 如果仅使用模板,则启用模板功能

c++ - 使特征成员特化的最便宜的方法是什么

node.js - Nodejs 邮件合并

c++ - 基本类型和复杂类型的通用 for 循环