0

I am reading caffe code and find it split C++ class Template code into hpp and cpp files. For example, Net.cpp includes the template class Net implementation code and Net.hpp includes the definition. But I remembered it is not possible to split a template class into hpp and cpp files, how does caffe make this work? Thank you.

XiongJi
  • 1
  • 1

2 Answers2

0

As you noted, template definitions cannot be split up as easily from the declarations without jumping through some hoops.

One common pattern is to split them up in different files for the human reader but essentially they are still defined all in one header. For example

Foo.h

#pragma once
template <typename T>
void Foo();  // declaration

#include "Foo.inl"

Foo.inl

template <typename T>
void Foo()
{
    // actual definition
}

Notice that the last thing in the .h file is to actually include the full contents of the .inl file. As far as the compiler is concerned, all of the template definitions are contained in the header to solve the initial problem you mentioned. But to the human reader, the declarations and definitions are separated.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

you can not "usually" separate the template definition and deceleration. when the compiler instantiate the template it need to know exactly the definition and the declaration of the members that are used in the context. so if you only include the header file the compiler doesn't know how to instantiate the template for the template parameter.

A solution other than the one that coryKramer mentioned is after the full definition (in the .cpp file) explicitly instantiate the template for the template parameters that you need, this way the template is already instantiated for the values that you would like to use (at this point we have the full declration and definition of template). However, note that if the template is need to be instantiated for other values you may encounter errors as compiler doesn't know how to do this process if the template is not fully defined in that file!

This is the method that is used in caffe via INSTANTIATE_CLASS(Net) macro at the end of .cpp file.

  • Thank you, I just looked up the code and you are correct. How does caffe handle function template such as functions in caffe/util/math_functions.cpp and math_functions.hpp? – XiongJi Jun 15 '17 at 15:34