1

Being new to C++, I was wondering what the best practices are regarding generic functions. I'm trying to implement a global function that takes as arguments a vector of generic data points, a function that maps one such data point to a different generic type as well as a generic pointer to return the mapped data point:

template <class Parameter_T, class Data_T, class CalculateParameterF>
void example(vector<Data_T> data,
        CalculateParameterF calculateParameters,
        Parameter_T& bestFittingParameters);

Now to my question: If I put the above declaration in a header file and its implementation in a .cpp file, the code won't compile. If I understand correctly, the compiler doesn't understand how it should compile the generic function exactly. In order to give it some hints, I can either leave the implementation body in the header file or add a second declaration filling in the specific types that I want to use it with. However, both of these solutions seem to be a bit ugly. Are these really the only solutions or am I missing something? If no, what solution should I prefer and why?

lbrndnr
  • 3,361
  • 2
  • 24
  • 34
  • ...well maybe not a dupe, but at least closely related – 463035818_is_not_an_ai Nov 24 '17 at 14:44
  • You just put the implementation in the header. You can use a `.impl` file and `#include` that in the header, but it doesn't solve anything. For the specific function look at [`std::transform`](http://en.cppreference.com/w/cpp/algorithm/transform) because it sort of does something similar and you can let yourself be inspired by it's choices. – nwp Nov 24 '17 at 14:44
  • 3
    Since the question asks about best practices, unless your function specifically takes advantage of some feature unique to `std::vector` (`reserve` perhaps?) the best practice is to accept iterators to a range and to template for iterators rather than containers. – François Andrieux Nov 24 '17 at 14:45
  • @FrançoisAndrieux The function is really only an example. I know that I could solve it differently but I'm required to implement it as part of an assignment. – lbrndnr Nov 24 '17 at 14:47
  • 1
    "I know that I could solve it differently" then it is rather unclear what is the question – 463035818_is_not_an_ai Nov 24 '17 at 14:54

0 Answers0