2

I have a link-time problem when I include a templated and non-templated class in the same .cpp file.

I went through the C++ FAQ 35.13,35.14,35.15 and it doesn't solve the problem.

http://www.parashift.com/c++-faq-lite/separate-template-class-defn-from-decl.html

I'm using Xcode 5 with clang.

Here's the example

barfoo.h

class bar{
public:
   void barfunc();
};

template <class T>
class foo{
public:
   void foofunc();
};

Here's the cpp file:

barfoo.cpp

void bar::barfunc(){...my code...}
template <class T>
void foo<T>::foofunc() {...my code...}
//I also put a instance of template class foo in the .cpp file
template class foo<int>;
//But is still generates the link error

The error is

clang: error: linker command failed with exit code 1 (use -v to see invocation)

But when I remove the bar class, the error disappears, can anyone tell me why it generates this error?

Put the definition in the header file could solve the problem, but it may cause another problem that is code bloating, does anyone can give another solutions?

4

1 回答 1

1

我发现了问题,问题是我没有将模板类实例化为我在代码中使用的类型。

以下是解决模板实例化问题的解决方案:

  1. 将定义放在头文件中,以便编译器具有实例信息。(缺点,增加加载和编译时间)

  2. 实例化代码中使用的所有类型

于 2015-02-06T16:54:13.923 回答