Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing C++ template function definitions in a .CPP file

Tags:

c++

templates

I have some template code that I would prefer to have stored in a CPP file instead of inline in the header. I know this can be done as long as you know which template types will be used. For example:

.h file

class foo { public:     template <typename T>     void do(const T& t); }; 

.cpp file

template <typename T> void foo::do(const T& t) {     // Do something with t }  template void foo::do<int>(const int&); template void foo::do<std::string>(const std::string&); 

Note the last two lines - the foo::do template function is only used with ints and std::strings, so those definitions mean the app will link.

My question is - is this a nasty hack or will this work with other compilers/linkers? I am only using this code with VS2008 at the moment but will be wanting to port to other environments.

like image 679
Rob Avatar asked Sep 22 '08 15:09

Rob


People also ask

Can I define template function in CPP?

Defining a Function TemplateA function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.

What is the main problem with templates C++?

C++ templates can't use normal run-time C++ code in the process of expanding, and suffer for it: for instance, the C++ factorial program is limited in that it produces 32-bit integers rather than arbitrary-length bignums.

Why templates are defined in header files?

To have all the information available, current compilers tend to require that a template must be fully defined whenever it is used. That includes all of its member functions and all template functions called from those. Consequently, template writers tend to place template definition in header files.

Can template function be overloaded C++?

You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.


1 Answers

The problem you describe can be solved by defining the template in the header, or via the approach you describe above.

I recommend reading the following points from the C++ FAQ Lite:

  • Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?
  • How can I avoid linker errors with my template functions?
  • How does the C++ keyword export help with template linker errors?

They go into a lot of detail about these (and other) template issues.

like image 148
Aaron N. Tubbs Avatar answered Sep 23 '22 15:09

Aaron N. Tubbs