0

I'm learning c++ and I'm working with templates. When I declare function in a header file with template, and implement it in cpp, it keeps saying "undefined reference to void do_something<SomeEnum>()"

.h file:

enum SomeEnum {
    Yes,
    No,
    Maybe
};


template<SomeEnum someEnum>
void do_something();
void do_something();

.cpp file:

#include "test.h"
#include "stdio.h"


template<SomeEnum someEnum>
void do_something() {
    printf("%d\n", someEnum);
}


void do_something() {
    printf("...\n");
}

main file:

...main function
do_something(); // no error
do_something<Yes>(); // thrown an error
Nicol Bolas
  • 413,367
  • 61
  • 711
  • 904
James Urian
  • 77
  • 2
  • 7
  • 4
    Does this answer your question? [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Stephen Newell Jul 02 '21 at 15:51

1 Answers1

0

Typically, templated functions are defined in the header file as well, although if you are adamant about keeping the declaration and definition separate, you can #include ".cpp" after your templated declaration in the header file. (See Why can templates only be implemented in the header file? for more).

mdf
  • 104
  • 7
  • 1
    See also [Why should I not include cpp files](https://stackoverflow.com/questions/1686204/why-should-i-not-include-cpp-files-and-instead-use-a-header). – rustyx Jul 02 '21 at 16:16
  • @rustyx -- that link involves a different issue. It's about `#include`ing source files in order to avoid linking. The `.cpp` files here are template definitions, which more typically use extensions like `.ipp`. – Pete Becker Jul 02 '21 at 17:23