0

Is it preferred to place the body of a template function in the header file or its corresponding cpp file and why?

I have some code that I slightly modified, thanks to the answer written by Nikos Athanasiou found on this thread and is seen below. Currently, I have all the below code in a single header file.

I have read the threads out there explaining how you can have the template function definition in the header file and template function body in the cpp file, but I am wondering which would be considered correct. Are there any performance pros and cons to either option?

typedef std::chrono::duration<float> fsec;

template<typename F, typename... Args>
float ftime_fsec(F func, Args&&... args){
    auto t1 = std::chrono::high_resolution_clock::now();
    func(std::forward<Args>(args)...);
    return std::chrono::duration_cast<fsec>
        (std::chrono::high_resolution_clock::now() - t1).count();
}
Community
  • 1
  • 1
  • If it's a template method you have to keep it in the header file. That can't be rendered into machine code until it's instantiated somehow. That's when the compiler has an idea of what the concrete implementation is going to look like. – tadman Feb 10 '17 at 01:35
  • 1
    Possible duplicate of [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Amadeus Feb 10 '17 at 01:36
  • 1
    I saw that thread; however, the thread explicitly mentions that you do not need to put the implementation in the header file and that same answer provides a solution so as to place it in the cpp file. My question is more of weather or not it is proper or even worth moving the implementation to a cpp file. Thanks! –  Feb 10 '17 at 01:42
  • @hbchevelle68 Maybe that answer could help: http://stackoverflow.com/a/16493574/2293156 – Amadeus Feb 10 '17 at 17:23
  • Awesome! Thanks for the link! –  Feb 10 '17 at 19:03

1 Answers1

0

It is definitely proper to put it into a header file. It is something that is meant to save you from typing redundant code, and it is also meant to be used as a declaration of a sort of "guide" for the compiler. It does not actually define anything in the object sense, it just serves a guideline for a later definition with a stated type.

gasoline
  • 74
  • 1
  • 7