c++ - 未定义的“函数引用”

标签 c++ templates error-handling

#include <iostream>
using namespace std;

void doStuff();

int main() {
    doStuff();
    return 0;
}

template<typename T>
void doStuff() {
    T k = 6;
    cout << k << endl;
} 

你好。我被这个错误困住了。每次我都会收到类似“未定义的 doStuff 引用”的错误。这个问题有解决办法吗?

最佳答案

doStuff()的声明表示非模板函数,定义是函数模板的定义,它们不匹配。

我想你想要的是函数模板,那么

template<typename T>
void doStuff() {
    T k = 6;
    cout << k << endl;
} 
int main() {
    doStuff<int>();
    return 0;
}

您还可以将声明放在 main() 之前,将定义放在 main() 之后。例如

template<typename T>
void doStuff();
int main() {
    doStuff<int>();
    return 0;
}
template<typename T>
void doStuff() {
    T k = 6;
    cout << k << endl;
} 

注意,调用doStuff时需要指定模板参数,因为它无法自动推导。

关于c++ - 未定义的“函数引用”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44042125/

相关文章:

c++ - 为类的每个实例分配唯一 ID

c++ - 如何在 win32 上刷新 stdlib 输出文件?

c++ - 调用模板基类的模板函数

android - 如何自动化Android项目骨架的创建? (没有安卓工作室)

javascript - 如何在异步操作期间使 Express.js 记录错误

coldfusion - 在onError函数中引发错误时,为什么没有递归无限循环?

c++ - 如何读取 XSD 架构元素 <xs :schema 的 'Version' 属性

c++ - C++中按引用和值传递

php - PHP的输入类错误处理?

templates - html/template if 范围索引子句