lundi 9 octobre 2017

Why is std::modulus defined such that it only works for integer-numbers and not for floating point

From C++ Reference I take that std::modulus is defined such that it behaves like (for C++11)

template <class T> struct modulus {
   T operator() (const T& x, const T& y) const {return x%y;}
   typedef T first_argument_type;
   typedef T second_argument_type;
   typedef T result_type;
};

This means, that due to the use of % it can only be used for integer numbers. Is there a reason why it is not implemented such, that it could be used for floating point numbers as well?

Maybe I am missing the point, so all hints are very appreciated.

EDIT to reply to comment: So to give an example of what I would whish for with floating point numbers which is derived from the example from C++ Reference:

// modulus example
#include <iostream>     // std::cout
#include <functional>   // std::modulus, std::bind2nd
#include <algorithm>    // std::transform

int main () {
    float numbers[]={1.,2.,3.,4.,5.};
    float remainders[5];
    std::transform (numbers, numbers+5, remainders,    std::bind2nd(std::modulus<double>(),2.5));
    for (int i=0; i<5; i++)
        std::cout << numbers[i] << " is " <<    (remainders[i]==0?"even":"odd") << '\n';
    return 0;
}

But obviously this causes a compiler error like:

error C2296: '%' : illegal, left operand has type 'const double'
1>          C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xfunctional(69) : while compiling class template member function 'double std::modulus<_Ty>::operator ()(const _Ty &,const _Ty &) const'
1>          with
1>          [
1>              _Ty=double
1>          ]
1>          main.cpp(16) : see reference to class template instantiation 'std::modulus<_Ty>' being compiled
1>          with
1>          [
1>              _Ty=double
1>          ]
1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xfunctional(70): error C2297: '%' : illegal, right operand has type 'const double'

Aucun commentaire:

Enregistrer un commentaire