Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[C++14] So I had some fun with templates and averages...
#1
... and wrote this:
    C++-Code:
template <typename Type,size_t ArraySize>
constexpr size_t size(const Type(&)[ArraySize]){
    return ArraySize;
}
 
template <typename Cont>
//requires std::Container<Cont>
inline auto size(const Cont &cont){
    return cont.size();
}
 
template <typename Cont>
//requires std::Container<Cont>
auto average(const Cont &cont){
    auto Sum = decltype(*std::begin(cont))(0);//deduce the return type, ugly hack, ISO committee please...
 
    for(auto &e:cont) Sum += e;
 
    return Sum/size(cont);
}
 
template <typename Ret,typename Cont>
//requires std::Container<Cont>
Ret average(const Cont &cont){
    Ret Sum = 0;
 
    for(auto &e:cont) Sum += e;
 
    return Sum/size(cont);
}

Basically it is a fully generalized algorithm for calculating the average of the elements within a container, which works on any container type.
The "requires" comments are based on the "Concepts Lite TS", so if it where to be available you'd be able to remove the "//" and the compiler would check that you are only passing containers to the function. I'm not entirely certain whether or not the concepts would belong to the "std" namespace.

I'm just wondering if anyone found this useful, funny, interesting, etc. and if you did please post a reply.
If you have suggestions for the code feel free to post a reply with them. I don't necessarily recommend that all your code looks like this though, as it would quickly get very messy.

Usage:
    C++-Code:
#include <iostream>
#include <vector>
 
using namespace std;
 
int main(){
    int Array[] = {4,2,3,4,8,9,7,2,1};
 
    cout << average(Array) << endl;//prints 4
    cout << average<float>(Array) << endl;//prints "4.444444"
 
    vector<float> Vector = {4.2f,2.3f,8.9f,4.6f,7.8f,6.1f};
    cout << average(Vector) << endl;//prints 5.65
 
    return 0;
}


Edit: Just realized I forgot to write "std::" before "begin" in my code above, so I fixed it.
Age ratings for movies and games (and similar) have never been a good idea.
One can learn a lot from reinventing wheels.
An unsound argument is not the same as an invalid one.
volatile in C++ does not mean thread-safe.
Do not make APIs unnecessarily asynchronous.
Make C++ operator > again
Trump is an idiot.
Reply
Thanks given by: A-Man


Messages In This Thread
[C++14] So I had some fun with templates and averages... - by Som1Lse - 01-27-2015, 06:11 PM



Users browsing this thread: 1 Guest(s)