Link error using templates

前端 未结 2 928
清酒与你
清酒与你 2020-12-11 13:16

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?

<
2条回答
  •  一向
    一向 (楼主)
    2020-12-11 13:45

    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 inline bool foo (const T& left, const T& right)
    {
      return true;
    }
    

    Put this in your main.cpp

    #include 
    #include "foo.h"
    
    int main ()
    {
      int left = 1;
      int right = 2;
    
      if (foo  (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?

提交回复
热议问题