How to define template function in source file

时间:2018-06-04 17:18:56

标签: 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>()`"

1 个答案:

答案 0 :(得分:0)

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.