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
  • 449,505
  • 63
  • 781
  • 982
James Urian
  • 123
  • 3
  • 7
  • 5
    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

2 Answers2

1

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
  • 133
  • 8
  • 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
  • 1
    @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
1

I use this format for such codes

Memory.hpp

#ifndef __MEMORY_HPP__
#define __MEMORY_HPP__
    
    class Memory
    {
        public:

        Memory();

        template <uint8_t y, uint8_t x>
        void getMem(uint8_t (&data)[y][x]);

        template <uint8_t y, uint8_t x>
        void setMem(uint8_t (&data)[y][x]);
    };

#define __MEMORY_CPP__
#include "Memory.cpp"
#undef  __MEMORY_CPP__
#endif

Memory.cpp

#ifndef __MEMORY_CPP__
#include "Memory.hpp"

    Memory::Memory()
    {
    }

#else

    template <uint8_t y, uint8_t x>
    void Memory::getMem(uint8_t (&data)[y][x])
    {
    }

    template <uint8_t y, uint8_t x>
    void Memory::setMem(uint8_t (&data)[y][x])
    {
    }

#endif