Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define template function in source file [duplicate]

Tags:

c++

templates

How can I declare template function in header file and define in source file?

// foo.h
template<typename T>
bool foo();

// foo.cpp
template<typename T>
bool foo()
{
    return false;
}

// main.cpp
bool bar = foo<int>();

I've got this so far. It compiles, but fails at linker: "undefined reference to `bool foo<int>()`"

like image 333
Martin Heralecký Avatar asked Sep 14 '26 20:09

Martin Heralecký


1 Answers

You can't. But there is a workaround if you really want seperate files:

Foo.tpp

template<typename T> void foo()
{

}

Foo.hpp

#ifndef FOO_HPP_
#define FOO_HPP_

template<typename T>
void foo();

#include "Foo.tpp";

#endif

main.cpp

#include "Foo.hpp"

int main()
{
    foo<int>();
}

Basically you put the implementation in a seperate file that is not recognised by the compiler, and you include that at the end of your header.

like image 69
MivVG Avatar answered Sep 16 '26 10:09

MivVG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!