cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

[C++ weekly]: Hiding implementation details with template specialization

Open ricardomatias opened this issue 1 year ago • 2 comments

Channel "C++Weekly"

Topics What is the appropriate way of hiding implementation details with template specialization?

Imagine you have the following function declaration inside a header file:

// distribution.h
template <std::size_t S>
std::array<float_t, S> createDecreasingOdds(int k);

template <std::size_t S>
std::array<float_t, S> sumDistribution(const std::array<float_t, S> &probabilities)

// Relevant for code block further down
template <std::size_t S>
std::array<float_t, S> decreasing(int k);

// usage
// auto odds = createDecreasingOdds<10>(10);
// auto distribution = sumDistribution(odds);

In the end this function will be used in another function to compose the final behavior that you actually want to expose (as a library f.ex) to the user. The problem is that the implementation can't be inside a .cpp file due std::size_t N, which would have to be implemented for every number needed (which is unknown, therefore might as well be considered infinite). If a class is considered, then that defeats the purpose as well, because you'd need different instances of the same class specialized to the size of the desired container (referring here to std::size_t N.

Example of what is wanted:

// SomeFile.cpp
#include "distribution.h"

// sumDistribution -> not accessible
// createDecreasingOdds -> not accessible

decreasing<10>(10); // accessible

The episode should be about what needs to be done in the perspective of someone making a library and how to approach this problem.

Length Bite-Sized

ricardomatias avatar Jan 17 '24 12:01 ricardomatias