【问题标题】:pointers as template arguments in c++指针作为 C++ 中的模板参数
【发布时间】:2015-10-23 15:54:38
【问题描述】:

我从以下代码中得到一个未解析的外部符号“reducedFraction(uint64_t*,uint64_t*)”的链接错误。

在 main.cpp 我有:

template <typename T>  T greatestCommonFactor(T a, T b) {
    //make b the smaller
    T t;//temp
    if (b > a)
    {
        t = a;
        a = b;
        b = t;
    }
    //archimedes method
    while (b != 0)
    {
        t = b;
        b = a % b;
        a = t;
    }
    return a;
}

template <typename T>
void reduceFraction(T *a, T *b) {
    T gcf = greatestCommonFactor(*a, *b);
    *a /= gcf;
    *b /= gcf;
}

int main() {
    uint64_t numerator;
    uint64_t denominator;

    numerator = 121;
    denominator = 55;
    cout << numerator << " " << denominator << endl;

    reduceFraction(&numerator, &denominator);

    cout << numerator << " " << denominator << endl;
}

当我将“uint64_t”作为非模板函数而不是“T”时,函数 bestCommonFactor 和 reduceFraction 工作正常。事实证明,当我将 reduceFraction 更改为非模板函数时,链接错误现在与 bestCommonFactor 相关。

将reduceFraction的第一行改为

auto gcf = greatestCommonFactor(*a, *b);

不成功。

我做错了什么?很明显,我正在尝试减少一小部分。当我将代码编写为非模板函数时,它工作得很好。提前致谢。

LNK2019 unresolved external symbol "void __cdecl reduceFraction(unsigned __int64 *,unsigned __int64 *)" (?reduceFraction@@YAXPA_K0@Z) referenced in function _main  visualStudioEuler   C:\Users\George\Documents\Visual Studio 2015\Projects\visualStudioEuler\visualStudioEuler\main.obj  1

一些旁注: 我在 Windows 10 上使用 Visual Studio 社区,代码是从 CodeLite“移植”的,如果有帮助的话。因此,我在使用“stdafx.h”和其他头文件时遇到了一些麻烦。

【问题讨论】:

  • 你用的是什么编译器?
  • 你的代码seems to work fine(也就是说,如果你提供greatestCommonFactor()的定义)(另外,你正在使用MSVC......但我认为即使是MSVC也能够编译此代码 ;) )
  • @865719 I second that
  • 请将您的问题edit发送至minimal reproducible exampleSSCCE (Short, Self Contained, Correct Example)。因为现在这个错误是不可重现的。
  • 这真的是您要编译的代码吗? reduceFraction 真的和main 函数在同一个文件中,还是reduceFraction 在单独的文件、库中?

标签: c++ templates pointers arguments


【解决方案1】:

代码现在可以工作了。问题出在头文件上。与“stdafx.h”有关。抱歉,我目前无法给出更好的答案。仅在其他人遇到类似问题并且不确定他们的代码时才发布此内容。谢谢大家的帮助!

【讨论】:

    猜你喜欢
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    相关资源
    最近更新 更多