Circular Inclusion with Templates

ε祈祈猫儿з 提交于 2019-12-18 12:44:28

问题


The following code compiles perfectly:

// MyFile.h

#ifndef MYFILE_H_INCLUDED
#define MYFILE_H_INCLUDED

template <typename Datatype>
class MyClass
{
    public:
    void MyMethod();
}

#include "MyFile.cpp"

#endif

// MyFile.cpp

#ifndef MYFILE_CPP_INCLUDED
#define MYFILE_CPP_INCLUDED

#include "MyFile.h"

template <typename Datatype>
void MyClass<Datatype>::MyMethod()
{
    // ...
}

#endif

The definitions of other methods and functions can be separated from the declarations in the same manner. Are there any downsides to using this approach? Can this behavior be relied upon?


回答1:


If you include the MyFile.tpp (I renamed it from .cpp), then you don't need to include the MyFile.h. #includeing a file is like exactly copying it's content into the file where it's included. Other from that, it's a common practice to organize the headers a bit. (Though you don't need the include-guards in the MyFile.tpp, because it should only ever be included from another header directly (like GMan says).)




回答2:


  • Rename the file "MyFile.cpp" to "MyFile.tpp".
  • Remove the include guards from "MyFile.tpp"
  • Change the include in "MyFile.h" so it is "MyFile.tpp"
  • Remove the the include inside "MyFile.tpp"

Note: Because the file is a *.tpp file (not *.cpp) it should not be included by other build system operations. If you have added it manually remove it.

Make sure the only place that includes <X>.tpp is the last line in <X>.h



来源:https://stackoverflow.com/questions/5467785/circular-inclusion-with-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!