Created
December 11, 2015 22:51
-
-
Save goldsborough/78ed9f6ec2d1f7af8d77 to your computer and use it in GitHub Desktop.
A generic averaging function using TMP.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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