Error in Template function in header file

I want to create a template function that would retrieve different data type input from cin

I defined a function like this in my header file
util.h
1
2
3
4
5
6
7
8
9
#ifndef UTIL_H
#define UTIL_H
namespace util
{
    template <typename T>
    void getConsoleInput(T arg, const char *message);

}
#endif 


My implementation
util.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include "util.h"

template <typename T>
void util::getConsoleInput(T arg, const char *message)
{
    {
        while (true)
        {
            T input{};
            std::cin >> input;

            if (input != arg)
            {
                std::cerr << message;
            }
            else
            {
                std::cout << "Match!";
                break;
            }
        }
    }
}


And my driver file
testDriver.cpp

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include "util.h"

int main()
{
    std::cout << "Do you agree (Please enter 'y' or 'n'): ";
    util::getConsoleInput('y', "Does not match!");
	
	std::cout << "Enter default keycode: ";
    util::getConsoleInput(1234, "Does not match!");
    return 0;
}


But I am having this error:

C:/cpp-workspace/testDriver.cpp:9: undefined reference to `void util::getConsoleInput<char>(char, char const*)'
collect2.exe: error: ld returned 1 exit status

If I remove my header file and put everything in my testdriver.cpp, I don't have any issues but putting it in header files is encountering some problem.

Any hints?
Don't separate out template definitions into their own implementation file.
The reason for this is that the compiler must know the full definition of the template in order to generate a function.

In other words, move the contents of util.cpp into util.h, and delete util.cpp.

More details at:
Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?
https://isocpp.org/wiki/faq/templates
Last edited on
Hi, Thank you very much for the link. So that's how it is.

As an aside, is it perfectly normal to put the template definition in my header file since I cannot separate it?

I often see header files contains function declarations or global constants enums or variables?

I created a namespaced utility functions that will be used by multiple cpp files so I have added it in the header and named it util.h.
Not just normal, it is required so the compiler knows how to generate the function at compile time. Even if the header is included into multiple source files.

That is how templates work in C++.

Well, you could manually copy'n'paste the block of templated code into every single source file that uses the function, but why not let the preprocessor do the pasting job for ya?
Last edited on
OK got it! Kudos and thank you all for being so helpful to c++ newbies like me!
Topic archived. No new replies allowed.