c++ - 具有多个模板定义的库

标签 c++ visual-studio-2010 function templates static-libraries

我正在学习如何使用 Visual Studio 2010 创建库。所以为了测试多个符号,我只写了 -

添加.cpp

template <typename T>
T fooBar(T a1, T a2)
{
  return (a1+a2);
}

减法.cpp

template <typename T>
T fooBar(T a1, T a2)
{
  return (a1-a2);
}

据我了解,模板是一个编译时概念。只是为了测试该工具在函数/函数模板之间的行为,我写了上面的内容。它成功地创建了 .lib,即使在为函数模板设置的最高级别上也没有任何警告。然而,如果功能正常,它会发出警告。

add.obj : warning LNK4006: "int __cdecl fooBar(int,int)" (?fooBar@@YAHHH@Z) already defined in subtract.obj; second definition ignored

add.obj : warning LNK4221: no public symbols found; archive member will be inaccessible

为什么该工具对于函数和函数模板的行为不同?

最佳答案

因为它们是模板化函数,所以在您实际实例化模板函数之前,函数本身不会被编译。

例如,我只是将以下代码放入我的一个 .cpp 文件中,但没有使用它,并且 .cpp 文件的编译顺利进行(尽管明显的语法错误):

template <typename J>
int foobar(J junk)
{
#pragma message("Compiling foobar")
     ppp = 35;

     return 0;
}

直到我尝试使用以下方法编译它(即创建它的编译器实例):

int main(void)
{
     double x;
     int y = foobar(x);
     return 0;
}

我会遇到编译错误吗?

: error C2065: 'ppp' : undeclared identifier  

自己尝试一下,它可能会帮助您解释所看到的内容(至少在您提到的第一种情况下没有错误。)

关于c++ - 具有多个模板定义的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10305660/

相关文章:

c++ - 帮助用 gcc/g++ 编译

c++ - 要不要使用事件对象?

C++ - 清理后 Unresolved external symbol 错误

c++ - 无法在 Visual Studio 2010 中打开包含文件 'stdlib.h'

c++ - CHAR_BIT 的更好名称?

c++ - cURL CURLOPT_WRITEFUNCTION 是否从同一线程调用?

c# - 发生未知错误 8004005

python - 组合功能以减少查询

python - 接受标量或 numpy 数组作为参数的 python 函数

python - 缩写几个功能 - 指南?