这可能是一个愚蠢的问题,但我完全不知道提示。
代码位于.cpp文件中
template <typename T> void foo2(T){}
template void foo2<int>(int);
VS2017一直告诉我:找不到函数'foo2'的函数定义。但是,代码实际上在VS2017中工作,如果我运行它没有错误消息。我不知道它是否是特定于IDE的问题,或者是代码问题。因为它很烦人,有谁知道为什么出现提示以及如何解决它?谢谢!
=========更新===========
这是完整的代码(将实例化移动到.h文件,但仍然有相同的问题):
test.h
#pragma once
template <typename T> void foo2(T);
template void foo2<int>(int);
TEST.CPP
#include "test.h"
#include "stdafx.h"
template <typename T>void foo2(T){}
主文件
#include "stdafx.h"
#include "test.h"
int main()
{
int a = 1;
foo2(a);
}
我倾向于相信特定于IDE的问题。如果我要求VS显示可能的修复,它将在.cpp文件中创建以下代码:
template void foo2(int)
{
return template void();
}
这绝对是错的。甚至无法通过编译。
通过扩展代码,我明白了。
你真的想在.h文件中使用extern template void foo2<int>(int);
。在test.cpp中应该只有一个实例。 extern template
是C ++ 11中的新功能,所以虽然你的书可能还没有涵盖它,但它确实被VS2017所理解。