Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Created December 11, 2015 22:51
Show Gist options
  • Save goldsborough/78ed9f6ec2d1f7af8d77 to your computer and use it in GitHub Desktop.
Save goldsborough/78ed9f6ec2d1f7af8d77 to your computer and use it in GitHub Desktop.
A generic averaging function using TMP.
template<typename Accumulator, typename Divisor, std::size_t N>
class Average
{
public:
template<typename... Args>
constexpr auto operator()(Args&&... args)
{
return _average(Accumulator(), std::forward<Args>(args)...);
}
private:
constexpr auto _average(Accumulator sum)
{
return sum / static_cast<Divisor>(N);
}
template<typename Head, typename... Tail>
constexpr auto _average(Accumulator sum, Head&& head, Tail&&... tail)
{
sum = sum + std::forward<Head>(head);
return _average(sum, std::forward<Tail>(tail)...);
}
};
template<typename Accumulator = double, typename Divisor = double, typename... Args>
constexpr auto average(Args&&... args)
{
return Average<Accumulator, Divisor, sizeof...(args)>()(
std::forward<Args>(args)...
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment