Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

c++ - Link error using templates

I converted a function to a template, and started getting this error. I must not be understanding a limitation of templates. Can someone tell me why this is broken?

I am receiving this error:

Undefined symbols:
  "bool foo<int>(int const&, int const&)", referenced from:
      _main in file1.o
ld: symbol(s) not found

When I link the following code. The code is simplified, but still fails. The first file contains:

#include <iostream>
template <class T> bool foo (const T&, const T&);

int main ()
{
  int left = 1;
  int right = 2;

  if (foo <int> (left, right))
    std::cout << "foo!" << std::endl;

  return 0;
}

And the second file contains:

template <class T> bool foo (const T& left, const T& right)
{
  return true;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For the reason Uri gave, template methods are usually defined in the header file. Because yours is a function and not a method of a class, explicitly define it (in the header file which may be included by more than one CPP file) as static or inline.

Put this in your foo.h

template<class T> inline bool foo (const T& left, const T& right)
{
  return true;
}

Put this in your main.cpp

#include <iostream>
#include "foo.h"

int main ()
{
  int left = 1;
  int right = 2;

  if (foo <int> (left, right))
    std::cout << "foo!" << std::endl;

  return 0;
}

The cpp code now sees the whole declaration of the template function.

Other solutions are listed here: How can I avoid linker errors with my template functions?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...