1

I have the following code (based on this answer):

#include <iostream>
#include <vector>

class Debug
{
public:
    template <typename T, typename A>
    static void printVector(const std::vector<T,A>&, const std::string& = "Vector:");
};

template <typename T, typename A>
void Debug::printVector(const std::vector<T,A>& v, const std::string& message)
{
    std::cout<<message<<std::endl;
    for(auto item : v)
    {
        std::cout<<item<<std::endl;
    }
}

int main() {
    std::vector<std::string> vec {"a","b","c"};
    Debug::printVector(vec);
    return 0;
}

It works great in an online compiler. However, when I try to compile it with GCC 4.8 on Ubuntu, it says:

error: undefined reference to `void Debug::printVector<std::string, std::allocator<std::string> >(std::vector<std::string, std::allocator<std::string> > const&, std::string const&)'
error: collect2: error: ld returned 1 exit status

Without the template (using simply std::vector<std::string>) everything works fine.

user2513149
  • 850
  • 12
  • 15
  • 2
    Does your actual code have the template definition in a separate file? – molbdnilo Jun 10 '19 at 05:07
  • @molbdnilo, yes, class definition is in a `.h` file which is then included in the `.cpp`. – user2513149 Jun 10 '19 at 05:11
  • 4
    The definition of the class and the definition of the function template are separate things. I suspect that you have encountered the issue of [why templates can only be implemented in the header file](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa). – molbdnilo Jun 10 '19 at 05:16

0 Answers0