开发者

Problem with file dependencies and templates on a C++ program [duplicate]

开发者 https://www.devze.com 2023-03-10 03:52 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: Templated function being reported as “undefined reference” during compilation
This question already has answers here: Closed 11 years ago.

Possible Duplicates:

Templated function being reported as “undefined reference” during compilation

Why can templates only be implemented in the header file?

Hi, I'm having a problem with dependencies in a c++ program that only originates when I use templates. Apparently the compiler is not able to instantiate the template for a concrete type and I don't know why.

Suppose I have this library (the real program where I find this is much bigger, but I think this seems to reproduce my original problem):

//temp.cpp file
#include "temp.hpp"

template <typename a> 
void printVector(std::vector<a> xs) {
  for_each(xs.begin(), xs.end(), [](a x) {std::cout << x << " ";});
}

void printDoubVector(std::vector<double> xs) {
  for_each(xs.begin(), xs.end(), [](double x) {std::cout << x << " ";});
}

with thi开发者_Go百科s header file:

#include <vector>
#include <algorithm>
#include <iostream>


template <typename a> void printVector(std::vector<a> xs);
void printDoubVector(std::vector<double> xs);

And this main file:

#include "temp.hpp"

int main(){
  std::vector<double> foo(10,1);
  printVector(foo);
  std::cout << std::endl;
}

When I compile them with this makefile:

CC=g++-4.5
FLAGS = -std=gnu++0x -Wall

all: test

test: temp.o main.o
    $(CC) $(FLAGS) $^ -o $@

%.o: %.cpp
    $(CC) $(FLAGS) -c $^ -o $@

I got a undefined reference to 'void printVector<double>(std::vector<double, std::allocator<double> >)' error.

Of course, if I do printDoubVector(foo); instead of printVector(foo);, it compiles normally. If everything's in the same file, it also compiles normally. I also tried to do printVector<double>(foo); with no result. Apparently the compiler knows I want a printVector<double>, he just can't find it. :(

I don't understand this problem. I was using templates in different files before without any problems at compilation. :( Yet, it feels like something very basic that I should know at this level. :/


The reason is described in detail here.

In short, you need to provide the full definition in the header-file, otherwise the compiler cannot instantiate the template.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号