D
D
Daniil Demidko2015-12-06 13:43:31
C++ / C#
Daniil Demidko, 2015-12-06 13:43:31

Why is it impossible to separate the methods of the template class?

MinGW compiler, codeblocks
Here is an example:
File Sample.h

#pragma once
template<typename T> class Example
{
 public:
     int Get();
};

Example.cpp File
#include"Example.h"
template<typename T> int Example<T>::Get() { return 4; }

main.cpp file
#include<iostream>
int main()
{
    Example<int> example;
    std::cout<<example.Get();
}

Issues:
undefined reference to 'Examle::Get()'

Moreover, when I do not include "Example.h" and leave main empty, everything compiles fine.
Or when I leave Get in Example.h everything works fine too:
File Sample.h
#pragma once
template<typename T> class Example
{
 public:
     int Get();
};
template<typename T> int Example<T>::Get() { return 4; }

I think the problem is not in the linker, because when I take out the methods of ordinary, non-template classes from the header in .cpp, everything works fine.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Armenian Radio, 2015-12-06
@Daniro_San

Bodies of template methods must be in *.h

V
Vitaly, 2015-12-06
@vt4a2h

You have already been answered above. I’ll add on my own that if you want to “put out” the implementation of methods somewhere (and in some cases you have to do this), then you can create a file with the tcc extension and include it in the header, but from below.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question