【问题标题】:create template for class method [duplicate]为类方法创建模板[重复]
【发布时间】:2012-09-08 22:39:15
【问题描述】:

可能重复:
Why do I get “unresolved external symbol” errors when using templates?
Why can templates only be implemented in the header file?

也许我太笨了,但这对我不起作用:

Foo.h

#ifndef FOO_H
#define FOO_H

class Foo {
public:
    template<typename T>
    void foo(T const &);
};

#endif // FOO_H

Foo.cpp

#include "Foo.h"

template<typename T>
void Foo::foo(T const &var) {
    // do something useless
}

ma​​in.cpp

#include "Foo.h"

int main() {
    int i;
    Foo bar;
    bar.foo(i);
}

我只是用 Xcode 4.4.1 编译,但它返回以下链接错误:

Undefined symbols for architecture x86_64:
  "void Foo::foo<int>(int const&)", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

感谢您的回复!

【问题讨论】:

标签: c++ class templates methods


【解决方案1】:

如果您不想打扰显式实例化,则必须提供内联定义。 另一种解决方案是在 .cpp 文件中提供显式实例化。

更多信息请参见http://www.parashift.com/c++-faq-lite/separate-template-fn-defn-from-decl.html

【讨论】:

    【解决方案2】:

    模板方法定义必须在实例化点可用。尝试将方法的定义放在头文件中。

    【讨论】:

    • 很想知道为什么你认为这会奏效。这是将实现与类的定义分开的标准方法,对吧?
    • @Vikdor Right...除非该方法是模板方法。
    • 谢谢! .cpp-文件中没有任何方法可以做到吗?
    • @Coodey 如果是模板,则不是。
    • 哦!谢谢,我从来不知道:(
    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-17
    • 1970-01-01
    • 2016-04-12
    • 2020-08-14
    相关资源
    最近更新 更多