1

I'm trying to work with deque and template and I wanted to add others files (func.cpp and func.h) so I can declare all my function in these files and then include func.h in main.cpp but I got an some errors: 1. argument list for variable template "display" is missing in main.cpp 2.'deque': undeclared identifier in func.cpp 3.'d': undeclared identifier in func.cpp

here's the main.cpp:

#include <iostream>
#include <algorithm>
#include <deque>
#include "funcr.h"

using namespace std;

int main()
{
    deque <int> d1{ 1,5,3,9 };
    d1.push_front(2);
    display(d1);
    return 0;
}

and here's the func.cpp:

#include <iostream>
#include <deque>

template<typename T>
void display(deque<T> d)
{
    for (auto e : d)
        std::cout << e << std::endl;
}

and there is the func.h:

#pragma once

template<typename T>
void display(deque<T>d);

can someone help me please?

  • Apart from template implementation in the header, the error in `func.cpp` is due the reason that `deque` in function argument should be `std::deque`. In addition, the header is included in the source file if you're trying to achieve the separate interface and implementation. And, in `main.cpp` the header file included is `funcr.h` but the actual file name is `func.h`. – Azeem Apr 18 '20 at 06:16
  • thanks, but if I declare it in header file, then I must declare a template in both header file and main.cpp, then it would be redundancy, is this right? –  Apr 18 '20 at 06:21
  • The template function would be defined in the header file (`func.h`) and it'll be included in `main.cpp`. You won't be declaring but including. – Azeem Apr 18 '20 at 06:45

1 Answers1

0

You must define display in func.h, because templated functions must be implemented in header files unless they are explicitly instantiated.

Also, you did not write using namespace std; in func.h (not that you should write it anywhere, especially headers). As a result, you need to write std::deque instead of merely deque.

So func.h should look like the following:

#include <iostream>
#include <deque>

template<typename T>
void display(const std::deque<T>& d)
{
    for (auto e : d)
        std::cout << e << std::endl;
}
Travis
  • 98
  • 1
  • 4
  • why I can't use an other file .cpp to implement the definition of display and in the header file(func.h) just the declaration? –  Apr 18 '20 at 06:28
  • Your question was closed. See the question that it's a duplicate of, as that will explain it. – Travis Apr 18 '20 at 06:34